swiftsknode

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


I have a scene with a number of children which are sub-classed SKNodes. I am trying to access a method for each of the child nodes, but am getting the error "Value of type 'SKNode' has no member '[member name]".

All on Swift 5 on Xcode 10.2 (if that's relevant?).

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
        }
    }
}

How can I access these methods from the Scene.children array? Is it possible or should I change tact?

Thanks!


Solution

  • It is said here that

    The children of an SKScene are of SKNode type. You want to access a property of an SKNode subclass. At compile time, the children are seen as SKNodes. You should try casting your child, something like

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

    Have in mind that downcasting is usually a code smell.