xcodeswiftcocos2d-iphonespritebuilder

My label won't update and is causing my game to crash


I'm very new to swift and coding in general, so any help is much appreciated! I have a CCLabelTTF as a score keeper of sorts, that is supposed to update every time you pass through and obstacle. The collision is working and the points seem to be increasing in my console correctly, but I'm trying to use this to update the actual CCLabelTTF that is displayed in the screen:

    func ccPhysicsCollisionBegin(pair: CCPhysicsCollisionPair!, hero nodeA: CCNode!, goal: CCNode!) -> Bool {
    goal.removeFromParent()
    points++
    scoreLabel.string = String(points) //the line appearing to cause the crash 
    return true
}

Im using SpriteBuilder and Xcode if that helps. Sorry if it is a dumb question!

Edit: Here is my scoreLabel declaration:

weak var scoreLabel : CCLabelTTF!

Solution

  • From your label's declaration, it probably means that your label is nil. Make sure you are adding the label in.

    To test it out, change your code to look like this:

    func ccPhysicsCollisionBegin(pair: CCPhysicsCollisionPair!, hero nodeA: CCNode!, goal: CCNode!) -> Bool {
        goal.removeFromParent()
        points++
        if scoreLabel != nil {
            scoreLabel.string = String(points)
            print("scoreLabel exists")
        } else {
            print("scoreLabel is nil")
        }
        return true
    }
    

    If it prints "scoreLabel is nil" in the console, the test confirms that your label doesn't exist.

    Edit

    You said you never initialized the label, so add this code in an appropriate function (viewDidLoad: or some equivalent in cocos-2d — I'm not that familiar with it):

    scoreLabel = CCLabelTTF(string: "", fontName: "FONT_NAME_HERE", fontSize: FONT_SIZE_HERE)