简体   繁体   中英

How to get name of object as string in swift 3.0

If my player collides with the drugNode object, I want to change the texture of the animation to the correct image. But I don't know how to get the name of "drugNode". My images are named "pill1", "pill2" and so on

func playerCollide(drugNode: SKSpriteNode, playerNode: SKSpriteNode){
        let animation = SKEmitterNode(fileNamed: "SpecialFallingParticle")!
        animation.position = drugNode.position

        print(String(describing: drugNode.self.name))
        animation.particleTexture = SKTexture(imageNamed: "\(String(describing: drugNode.name))")
        self.addChild(animation)
        self.run(SKAction.playSoundFileNamed("snacked.mp3", waitForCompletion: false))
        drugNode.removeFromParent()
    
        self.run(SKAction.wait(forDuration: 2)){
            animation.removeFromParent()
        }
    }

Output:

Optional("pill18")
2020-06-25 18:32:50.096389+0200 Snacker[5316:292543] SKTexture: Error loading image resource: "Optional("pill18")"
Optional("pill1")
2020-06-25 18:32:51.597661+0200 Snacker[5316:292543] SKTexture: Error loading image resource: "Optional("pill1")"
Optional("pill21")
2020-06-25 18:32:53.097427+0200 Snacker[5316:292543] SKTexture: Error loading image resource: "Optional("pill21")"

The name property of SKSpriteNode returns a String? , an optional String . You need to unwrap that. One option is to use the nil coalescing operator ?? to provide a default value if name has not been set:

let name = drugNode.name ?? "defaultImage"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM