3

I am a beginer and starting my first swift game. It seems like the GameScene.sks interface would be extrememly easy to position my labels and nodes for each level, but I am having trouble figuring out how to reference the nodes with swift. For example I dragged over a label to act as a timer, but I dont know how to update the label text with code. I was thinking something like:

func timerDidFire(){
    countDown--
    SKLabelNode.name("countDownTimerLabel").text = countDown
}
ABakerSmith
  • 22,759
  • 9
  • 68
  • 78
user4812000
  • 1,033
  • 1
  • 13
  • 24
  • Are you using an `NSTimer`? If you are, take a look at: [Spritekit - Creating a timer](http://stackoverflow.com/questions/23978209/spritekit-creating-a-timer). – ABakerSmith Jul 14 '15 at 00:00

1 Answers1

2

You need to use the childNodeWithName method on SKNode. For example:

func timerDidFire() {
    let label = childNodeWithName("countDownTimerLabel") as! SKLabelNode
    label.text = --countDown

    // I believe this is an appropriate case for force unwrapping since you're going to 
    // want to know if your scene doesn't contain your label node. 
}

Since you're going to be accessing the SKLabelNode often, and it takes time to search through the node tree (not very much but something to bear in mind), it may be a good idea to keep a reference to the label. For example, in your SKScene subclass:

lazy var labelNode: SKLabelNode = self.childNodeWithName("countDownTimerLabel") as! SKLabelNode

On a related note, if you're looking for multiple nodes there's the enumerateChildNodesWithName(_:usingBlock:), also on SKNode.

Finally, for more information have a look at Apple's WWDC 2014 talk: Best Practices for Building SpriteKit Games where they cover both the methods I mentioned.

ABakerSmith
  • 22,759
  • 9
  • 68
  • 78