如何从 SKNode.children 数组访问 SKNode 子类方法?

How do you access SKNode subclass methods from SKNode.children array?

我有一个场景有多个 children 是 sub-classed SKNodes。我正在尝试访问每个 child 节点的方法,但收到错误 "Value of type 'SKNode' has no member '[member name]"。

全部 Swift 5 Xcode 10.2(如果相关?)。

import SpriteKit

class GameScene: SKScene {

    override func didMove(to view: SKView) {

        let slim = NamedNode(name: "Slim Shady")
        let snoop = NamedNode(name: "Snoop Dog")
        let shaggy = NamedNode(name: "Shaggy")

        self.addChild(slim)
        self.addChild(snoop)
        self.addChild(shaggy)

        for child in self.children {
            child.whatsMyName()   
            // ERROR: Value of type 'SKNode' has no member 'whatsMyName'
        }
    }
}


class NamedNode: SKNode {

    var standup = false

    init(name: String) {
        super.init()
        self.name = name
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func whatsMyName() {
        print("My name is ", name as Any)
        if self.name == "Slim Shady" {
            standup = true
        }
    }
}

如何从 Scene.children 数组访问这些方法?有可能还是我应该改变策略?

谢谢!

It is said here that

一个SKScene的children都是SKNode类型。您想要访问 SKNode 子类的 属性。在编译时,children 被视为 SKNodes。 您应该尝试投射 child,例如

for child in self.children { (child as? NamedNode).whatsMyName() }

请记住,向下转换通常是一种代码味道。