iosswiftsprite-kitskscenesklabelnode

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!


Solution

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