如何在 swift 3.0 中获取对象名称作为字符串
How to get name of object as string in swift 3.0
如果我的播放器与 drugNode 对象发生碰撞,我想将动画的纹理更改为正确的图像。但我不知道如何获得“drugNode”的名称。我的图片命名为“pill1”、“pill2”等等
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()
}
}
输出:
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")"
SKSpriteNode
returns一个String?
name
属性一个String?
一个可选String
.你需要打开它。如果尚未设置 name
,一种选择是使用 nil 合并运算符 ??
提供默认值:
let name = drugNode.name ?? "defaultImage"
如果我的播放器与 drugNode 对象发生碰撞,我想将动画的纹理更改为正确的图像。但我不知道如何获得“drugNode”的名称。我的图片命名为“pill1”、“pill2”等等
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()
}
}
输出:
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")"
SKSpriteNode
returns一个String?
name
属性一个String?
一个可选String
.你需要打开它。如果尚未设置 name
,一种选择是使用 nil 合并运算符 ??
提供默认值:
let name = drugNode.name ?? "defaultImage"