Get child node from SKReferenceNode in SpriteKit SWIFT

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

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

My first idea was to directly invoke the node child:

 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 hit the firstSquare line:

 Fatal error: unexpectedly found nil while unwrapping an Optional value

How to get a child of a node in a reference scene?

+4
source share
1 answer

Try calling it with this code:

override func sceneDidLoad() {
     if let sprite = self.childNode(withName: "//square") as? SKSpriteNode {
           // do whatever you want with the sprite
     }
     ...
}
+6
source

Source: https://habr.com/ru/post/1650477/


All Articles