Search code examples
swiftsprite-kitsknode

Access SKCameraNode from a different class using Swift


I have created an SKCameraNode in my GameScene class and have added buttons to it as SKSpriteNodes. I then set the GameScene camera to be the SKCameraNode.

I have another custom Class called Player of type SKNode. From this Class I need to access the button nodes that are in the SKCameraNode which is inside the GameScene. How can I do this?

I can't create an instance of the GameScene class in my Player class as it needs the size argument and if I did I would have two different instances of the GameScene class.

Any help appreciated...


Solution

  • Once you add your player to the scene then you always have access to the scene. You have to make sure and try to access scene after your player was added or this code will make your game crash.

    within your Player class you can go

    (self.scene as! GameScene).yourCameraNode
    

    assuming yourCameraNode is a property of GameScene