Tom Wicks
Tom Wicks

Reputation: 1025

Change the text of a SKLabelNode added from the scene editor

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!

Upvotes: 2

Views: 2065

Answers (2)

Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

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
     }
}

Upvotes: 3

Tom Wicks
Tom Wicks

Reputation: 1025

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()
    }

}

Upvotes: 1

Related Questions