2

enter image description hereI want to change the text of a SKLabelNode created in the scene editor named myScoreLabel to update a score on collision of two objects. Here's the relevant code:

class holeOne: SKScene, SKPhysicsContactDelegate {

    var myScoreLabel: SKLabelNode!
    var myscore:Int = 0

    func addScore() {
        myscore += 1
        myScoreLabel.text = "\(myscore)"
    }

    func didBegin(_ contact: SKPhysicsContact) {
        addScore()
    }

}

At the moment after the collision the app crashes with "unexpectedly found nil while unwrapping an Optional value". What am I doing wrong and how can I do it right? Thanks!

Tom Wicks
  • 785
  • 2
  • 11
  • 28

2 Answers2

3

From code that you provide var myScoreLabel: SKLabelNode! is not created.

Try to create SKLabelNode firstly. And then set value.

Example:

myScoreLabel = SKLabelNode(fontNamed: "Chalkduster")
myScoreLabel.text = "Test"
myScoreLabel.horizontalAlignmentMode = .right
myScoreLabel.position = CGPoint(x: 0, y:10)
addChild(scoreLabel)

Or you can connect it from .sks scene.

override func sceneDidLoad() {
     if let label = self.childNode(withName: "myScoreLabel") as? SKLabelNode {
        label.text = "Test" //Must add '.text' otherwise will not compile
     }
}
Emm
  • 1,963
  • 2
  • 20
  • 51
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100
  • Ah ok thanks, i've added a screenshot for clarity I was hoping I could create it in the Scene editor rather than programmatically. Any idea how I would change the text of a SKLabelNode created in the scene editor? – Tom Wicks Apr 14 '17 at 19:01
1

Great, so in the end I did this:

class holeOne: SKScene, SKPhysicsContactDelegate {

    var myScoreLabel: SKLabelNode!
    var myscore:Int = 0

    func addScore() {
        myscore += 1

        if let myScoreLabel = self.childNode(withName: "myScoreLabel") as? SKLabelNode {
            myScoreLabel.text = "\(myscore)"
        }

    }

    func didBegin(_ contact: SKPhysicsContact) {
        addScore()
    }

}
Tom Wicks
  • 785
  • 2
  • 11
  • 28