Get child node of SKReferenceNode in SpriteKit SWIFT
Asked Answered
P

1

6

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 ?

Proteiform answered 7/8, 2016 at 19:35 Comment(3)
Where do you call this code? From an init mode (probably your scene is not ready to get his childs) or from didMoveToView?Hitt
From sceneDidLoad() in my GameScene.swiftProteiform
Take a look to this answer and let me know if it works.Hitt
H
10

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
     }
     ...
}
Hitt answered 8/8, 2016 at 14:4 Comment(2)
It works thanks. Can you explain me the "//" before "square"?Proteiform
Sure, this specifies that the search should begin at the root node and be performed recursively across the entire node tree. Otherwise, it performs a recursive search from its current position. You can find more details here: developer.apple.com/library/ios/documentation/SpriteKit/…Hitt

© 2022 - 2024 — McMap. All rights reserved.