hamobi hamobi - 4 months ago 30
iOS Question

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?

Answer

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

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