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