Mason
Mason

Reputation: 271

Tidy, Clean Access To SKNodes

I'm trying to tidy some of my SKScene code. Currently I have about 11 references to SKNodes (some are layers containing sub-nodes). These nodes and their sub-nodes are frequently accessed by the class. The way I considered doing this is:

Subclass all the SKNodes to another class, for example, currently I have layerPause: SKNode? defined at the top of the SKScene. This would become layerPause: PauseMenu where:

class PauseMenu: SKNode
{
lazy var lbBestTime: SKLabelNode = childNodeWithName("lbPersonalBest") as! SKLabelNode
}

Then, when the scene is loading I can simply use:

layerPause = pauseScene.childNodeWithName("pauseMenu")?.copy() as? SKNode

This would allow me to easily access important sub-nodes without calling childNodeWithName all the time. But unfortunately, the PauseMenu class gives an error saying I can't use childNodeWithName method.

Could someone point me in the right direction? Maybe there is a more elegant way to manage my nodes, or perhaps I'm missing something simple in the PauseMenu subclass as described above.

Many thanks,

Upvotes: 0

Views: 73

Answers (2)

rickster
rickster

Reputation: 126107

All that's missing here is self:

class PauseMenu: SKNode {
    lazy var lbBestTime: SKLabelNode = self.childNodeWithName("lbPersonalBest") as! SKLabelNode
}

In the context of a (lazy) property initializer, you can't leave self implicit... probably that initializer is being treated as a closure (even though it doesn't require braces if it's a single statement), and closures always need to be clear about whether they capture self.

If you're initializing layerPause as in your question, and its type is SKNode, you still won't be able to use your newly defined lbBestTime property on it, though — all the compiler knows is that layerPause is an SKNode. Be sure to tell it that layerPause is a PauseMenu, and then you can use your custom properties from that class.

Upvotes: 1

ABakerSmith
ABakerSmith

Reputation: 22939

So close, you just need to add an explicit self:

class PauseMenu: SKNode
{
    lazy var lbBestTime: SKLabelNode = 
        self.childNodeWithName("lbPersonalBest") as! SKLabelNode
}

Upvotes: 1

Related Questions