-2

I'm a beginner programmer. Please help. Can't find the value when unwrapping the childNode. Not sure why. Please help, thanks My code:

var someParentNode = SKSpriteNode()
var someChildNode = SKSpriteNode()
override func didMove(to view: SKView) {
someParentNode = self.childNode(withName: "someParentNode") as! SKSpriteNode
someChildNode = self.childNode(withName: "someChildNode") as! SKSpriteNode

Issue: Gets an error when its unwrapping the childNode (at the last line):

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Not sure why its an error. Like the name of the nodes suggest, childNode is a parent of someParentNode. Please help. Thanks in advance :)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
MyName
  • 31
  • 3
  • First of all you shouldn't don't force unwrap, learn how to implement unwrapping properly. Secondly, there is no way we can help you determine why `self.childnode(...` returns nil from the code you have supplied. There could be any number of reasons why the returned value is nil. – Joakim Danielson May 12 '18 at 13:38
  • Have you checked the names are correct, including lower/uppercase ? – claude31 May 12 '18 at 13:42

1 Answers1

1

The code someParentNode = self.childNode(withName: "someParentNode") as! SKSpriteNodeself.childNode(withName: "someParentNode") looks for an SKNode with a name "someParentNode". Bear in mind that this is the name you can assign to a node, as in someNode.name = "xyz". It does not refer to the name of the variable in the line var someParentNode = SKSpriteNode(). These are two different things.

Since there are no nodes where node.name == "someParentNode", the function self.childNode(withName: "someParentNode") returns nil. You then do a forced unwrap with as!, causing the error.

You don't need to call someParentNode = self.childNode(withName: "someParentNode") as! SKSpriteNode in didMove, since you have already created a new SKNode and assigned this new SKNode to someParentNode in the first line. So there is no need to assign it a new node anymore.

If you still want to find a node by name, then do someParentNode.name = "someParentNode" before calling self.childNode(withName: "someParentNode"), but this is not necessary because as explained above, you already created and assigned a new SKNode to someParentNode. Also, since you declared someParentNode outside of any function, it has global scope in your SKScene, and you can therefore access it in any method of that scene. Therefore, there is no need to use a method to look for the node, since you always have access to that node in your scene.

Hope this helps! The same reasoning applies to someChildNode

JohnV
  • 981
  • 2
  • 8
  • 18