循环遍历SKNode的所有孩子? [英] Loop through all children of an SKNode?
问题描述
我有一个带有多个子SKSpriteNodes的SKNode。一个简单的例子:
I have an SKNode with a number of child SKSpriteNodes. A simplified example:
var parentNode = SKNode()
var childNode1 = SKSpriteNode()
var childNode2 = SKSpriteNode()
self.addChild(parentNode)
parentNode.addChild(childNode1)
parentNode.addChild(childNode2)
我想对所有这些孩子运行 colorizeWithColor
操作。当我在 parentNode
上运行操作时,没有任何效果。
I want to run a colorizeWithColor
action on all of these children. When I run the action on parentNode
, there's no effect.
我不能使用 enumerateChildNodesWithName
在父项上,因为它的许多子项已经有我正在使用的名称。
I can't use enumerateChildNodesWithName
on the parent, because many of its children already have names I'm using.
有没有办法循环所有子项 parentNode
,为了对所有这些操作执行单个操作?
Is there a way of looping through all children of parentNode
, in order to run a single action on all of them?
推荐答案
您可以简单地枚举 parentNode.children
:
for child in parentNode.children as! [SKNode] {
// ...
}
如有必要,检查每个孩子是否实际上是 SKSpriteNode
:
If necessary, check each child if it is actually a SKSpriteNode
:
for child in parentNode.children {
if let spriteNode = child as? SKSpriteNode {
// ...
}
}
从 Swift 2(Xcode 7)开始,枚举和可选的强制转换可以与带有案例模式的for循环结合使用:
As of Swift 2 (Xcode 7), enumeration and optional cast can be combined with to a for-loop with a case-pattern:
for case let child as SKSpriteNode in parentNode.children {
// ...
}
这篇关于循环遍历SKNode的所有孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!