hamobi
hamobi

Reputation: 8130

Spritekit best way to get sprites scene inside of SKSpriteNode subclass

I'm subclassing SKSpritenode and need reference to the sprite's scene. Is there a way to detect when the sprite has been added to the scene.

let gameScene = self.scene as GameScene

doing this inside init throws optional error since my sprite has been instantiated but not added to the scene. How do I tell when my sprite has been added to the scene so I can set the property?

Upvotes: 2

Views: 824

Answers (2)

Knight0fDragon
Knight0fDragon

Reputation: 16827

Just use a guard

guard let scene = self.scene as? GameScene
else
{
    return
}
//Everything beyond here is safe to use scene

Upvotes: 0

Andrey Gordeev
Andrey Gordeev

Reputation: 32459

Usually I create addToNode:(SKNode *)parentNode method to handle that:

- (void)addtoNode:(SKNode *)parentNode {
     [parentNode addChild:self];
     // Do what you need here
}

Upvotes: 1

Related Questions