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 ?

Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
cmii
  • 3,556
  • 8
  • 38
  • 69

1 Answers1

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
     }
     ...
}
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
  • It works thanks. Can you explain me the "//" before "square"? – cmii Aug 08 '16 at 14:15
  • 4
    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: https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKNode_Ref/#//apple_ref/doc/uid/TP40013023-CH1-SW74 – Alessandro Ornano Aug 08 '16 at 14:17