按特定的班级名称搜索孩子

时间:2017-11-19 16:36:45

标签: swift class sprite-kit enumerate

在阅读apple doc关于搜索子节点后,我了解到我不仅可以通过节点的名称进行搜索,还可以通过其类来搜索 - 使用withName var中的project_name.class_name。我的项目名称是颜色,我有类名为SKShapeNode的类名BallNode。不幸的是我找不到使用这种方法的节点(正如在apple doc上写的那样)。在我的项目中,球是在屏幕上随机创建的,每个球的名字都是“BALL”,当我按名称搜索时(BALL)我可以找到节点,但如果我尝试使用类名,它只是起作用。 这是我的代码:

    override func update(_ currentTime: TimeInterval) {

    self.enumerateChildNodes(withName: "color.BallNode") { node, _ in
        print("ball node found")
    }

有人知道我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

来自Apple的链接确实显示了正确的代码。我刚刚在一个测试项目中尝试了以下代码并且它可以工作

    let ball = PushButton(upTexture: SKTexture(image:#imageLiteral(resourceName: "button")))
    ball.name = "ball1"
    addChild(ball)

    let ball2 = PushButton(upTexture: SKTexture(image:#imageLiteral(resourceName: "button")))
    ball2.name = "ball21"
    addChild(ball2)

    let ball3 = PushButton(upTexture: SKTexture(image:#imageLiteral(resourceName: "button")))
    ball3.name = "ball3"
    addChild(ball3)

    self.enumerateChildNodes(withName: "WordConstructor.PushButton") { node,_ in
            print("node.name \(node.name)")
    }

我会检查你的项目名称是" color"而不是"颜色"你的项目中有多个目标吗?

你能展示你把球添加到场景的代码吗?

在你的更新声明中运行它会导致你的游戏试图找到每秒60次,这可能不是很理想