cocoseis cocoseis - 5 months ago 45
Swift Question

Initializer used when loading nodes from SKS file

I am creating a subclass of

SKSpriteNode
e.g.
Player
and label a
SKSpriteNode
in my *.sks file with the custom class
Player
. In the *.swift I am loading the node using:
self.childNode(withName: "myNodesName")
. Well, this works fine, but I also want to modify the constructor used for this procedure.

Which constructor of
SKSpriteNode
is used if I access a
SKSpriteNode
in my *.swift file from its *.sks using

self.childNode(withName: "myNodesName") as? Player


?

Answer

What constructor gets called?

When a node is created from an sks file, then SpriteKit does use this initializer

init?(coder aDecoder: NSCoder)

How can you implement that into Player?

You have a Player class. You can implement the constructor this way

class Player: SKSpriteNode {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}