cmi cmi - 4 months ago 12
Swift Question

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 ?

Answer

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
     }
     ...
}