问题
I'm trying to change the color of every single instance of a node in SpriteKit. When I try to put it in the update method, it only changes one and not all of them.
override func update(currentTime: CFTimeInterval) {
if changeColor {
self.enumerateChildNodesWithName("blocks", usingBlock: { node, stop in
block?.color = UIColor.orangeColor()
})
}
}
回答1:
I think you should change the color of the node
, not of some block
variable. You will retrieve all SKNode
s with that name. But those nodes don't have a color property. Only some subclasses, for example the SKSpriteNode
have a color
property. You therefore have to add some additional logic to change the color. For example you could try to convert the node
to SKSpriteNode
and only then change the color
:
self.enumerateChildNodesWithName("blocks", usingBlock: { node, stop in
if let sprite = node as? SKSpriteNode {
sprite.color = UIColor.orangeColor()
}
})
As @appzYourLife correctly mentioned that code can be simplified / swiftyfied to
self.enumerateChildNodesWithName("blocks") { node, stop in
if let sprite = node as? SKSpriteNode {
sprite.color = .orangeColor()
}
}
来源:https://stackoverflow.com/questions/34699122/how-do-you-change-the-color-of-all-of-the-nodes-of-a-specific-name-in-spritekit