Can't link to Xcode GameScene.sks with swift
I start and start my first quick game. It looks like the GameScene.sks interface would be extremely easy to place my labels and nodes for each level, but I'm having a hard time figuring out how to handle nodes with swift. For example, I dragged the label to act as a timer, but I don't know how to update the label text using code. I was thinking something like:
func timerDidFire(){
countDown--
SKLabelNode.name("countDownTimerLabel").text = countDown
}
source to share
You need to use the method childNodeWithName
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 will be accessing a SKLabelNode
lot and it takes a little time to search the node tree (not very much, but something to remember), it might be a good idea to keep the shortcut reference. For example, in a subclass SKScene
:
lazy var labelNode: SKLabelNode = self.childNodeWithName("countDownTimerLabel") as! SKLabelNode
In the related note, if you are looking for multiple nodes enumerateChildNodesWithName(_:usingBlock:)
, also on SKNode
.
Finally, see Apple WWDC 2014: Best Practices for Making SpriteKit Games for more information , where they cover both of the methods I mentioned.
source to share