How do I access the children of a nested SKReferenceNode

Hello,


I have a GameScene.sks file which has an SKReference node that references my Level.sks file.


In my Level.sks file I have an SKSpriteNode named "player"


inside of the GameScene.swift file, I would like to know how to access my "player." Any ideas how to go about that?


I tried

class GameScene: SKScene {

     override func didMoveToView(view: SKView) {
          let level = childNodeWithName("level")
          let player = level!.childNodeWithName("player")
     }
}


level is not nil, but player returns nil


Thanks for your help!

Hi be-bert,


You should be able to access the player node directly...

let player = childNodeWithName("player")


cheers


Jim

Thanks for the response Jim, but that does not seem to work when I am trying to access children of a referenceNode.

Hi be-bert,


Apologies, I don't know of a way to reference an .sks file from an SKNode on a separate .sks file.

Could you elaborate on your setup in the GameScene.sks file please?

Sure thing Jim. Thanks again for your help.


I have the default template for when starting a spritekit game...

GameViewController which creates my GameScene.swf along with its .sks scene file, GameScene.sks

let scene = GameScene(fileNamed:"GameScene")...
skView.presentScene(scene)


I have another scene file called Player.sks that is added as an SKReferenceNode in the GameScene.sks editor (similar to how they do it in the "Whats New In SpriteKit" 2015 WWDC video).


I then try to access a few SKSpriteNodes that live my Player.sks from the GameScene.swift file

class GameScene: SKScene {

     override func didMoveToView(view: SKView) {
          let playerArm = childNodeWithName("Player Arm") // player was dragged into the GameScene.sks file as an SKReferenceNode
          //also tried
          let player = childNodeWithName("Player")
          let playerArm = player.childNodeWithName("Player Arm")
     }

)


It sounds kind of confusing maybe, but I hope that makes sense.

Accepted Answer

Hi be-bert,


Try this code...

let player = SKReferenceNode(fileNamed: "Player")
for node in player.children {
   print(node.childNodeWithName("Player Arm"))
}


I almost gave up on this one. But here it is, in the child node of the player reference node.

There is probably a more elegant way to access it. But still, it is accessible.


I hope this helps.

Jim


additional...

You can also use

let player = childNodeWithName("Player")
for node in player!.children {
   print(node.childNodeWithName("Player Arm"))
}

You can do this more directly by using the search patterns available for searching the node tree. In this case


let player = self.childNodeWithName("//player")


This will search from the root of the current scene recursively descending all child nodes (including reference nodes).

How do I access the children of a nested SKReferenceNode
 
 
Q