Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child node of SKReferenceNode in SpriteKit SWIFT

I create a scene Case.sks (using Level Editor), inside one SKSpriteNode (name : square), and one SKLabel (name : label). In my main scene, GameScene.sks, I use a SKReferenceNode with "Case" for reference.

I need to access to the "square" sprite from my main scene.

My first idea was to call directly the child node:

 let firstSquare = childNode(withName: "square") as! SKSpriteNode

But I got :

 Fatal error: unexpectedly found nil while unwrapping an Optional value

So I tried :

 let caseRef = childNode(withName: "Case") as! SKReferenceNode
 let firstSquare = caseRef.childNode(withName: "square") as! SKSpriteNode

But I got on the firstSquare line :

 Fatal error: unexpectedly found nil while unwrapping an Optional value

How can get a child node of a reference scene ?

like image 702
cmii Avatar asked Aug 07 '16 19:08

cmii


1 Answers

Try to call it with this code:

override func sceneDidLoad() {
     if let sprite = self.childNode(withName: "//square") as? SKSpriteNode {
           // do whatever you want with the sprite
     }
     ...
}
like image 157
Alessandro Ornano Avatar answered Oct 31 '22 22:10

Alessandro Ornano