xcode - 我的标签无法更新并导致我的游戏崩溃

标签 xcode swift cocos2d-iphone spritebuilder

我对 swift 和编码都很陌生,所以非常感谢任何帮助!我有一个 CCLabelTTF 作为某种记分器,它应该在你每次通过障碍时更新。碰撞正在起作用,并且点似乎在我的控制台中正确增加,但我正在尝试使用它来更新屏幕中显示的实际 CCLabelTTF:

    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
}

如果有帮助的话,我正在使用 SpriteBuilder 和 Xcode。抱歉,如果这是一个愚蠢的问题!

编辑:这是我的 ScoreLabel 声明:

weak var scoreLabel : CCLabelTTF!

最佳答案

从你的标签声明来看,这可能意味着你的标签是nil。确保您添加了标签。

要测试它,请将代码更改为如下所示:

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
}

如果在控制台中打印“scoreLabel is nil”,则测试确认您的标签不存在。

编辑

您说您从未初始化过标签,因此请将此代码添加到适当的函数中(viewDidLoad:或cocos-2d中的某些等效函数 - 我对此不太熟悉):

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

关于xcode - 我的标签无法更新并导致我的游戏崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35470240/

相关文章:

Xcode 说 "Uncommitted Changes"每当我尝试 git pull 或 push

ios - 移动层导致物理对象留在原地

c - xcode上C程序的逻辑错误

ios - 如何隐藏标签栏 Controller 第一个 View Controller 并直接转到下一个 Controller 但应在底部显示标签栏项目

ios - 将 UITextField 或按钮与 viewModel 绑定(bind)

objective-c - 此 bundle 无效 - 文件扩展名必须是 .zip

ios - 计算距离,转换为公里,然后去掉小数位

iphone - 为什么Cocos2D编程指南建议使用initWithTexture?

objective-c - CCSpriteFrameCache 优化

iphone - 加载文本时 UITextView.text 滞后