gpt4 book ai didi

ios - 更改从场景编辑器添加的 SKLabelNode 的文本

转载 作者:搜寻专家 更新时间:2023-11-01 06:16:38 35 4
gpt4 key购买 nike

enter image description here我想更改在名为 myScoreLabel 的场景编辑器中创建的 SKLabelNode 的文本,以更新两个对象碰撞的分数。相关代码如下:

class holeOne: SKScene, SKPhysicsContactDelegate {

var myScoreLabel: SKLabelNode!
var myscore:Int = 0

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

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

}

在碰撞后的那一刻,应用程序崩溃并显示“在展开可选值时意外发现 nil”。我做错了什么,我怎样才能做对?谢谢!

最佳答案

根据您提供的代码 var myScoreLabel: SKLabelNode! 未创建。

首先尝试创建SKLabelNode。然后设置值。

例子:

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

或者您可以从 .sks 场景连接它。

override func sceneDidLoad() {
if let label = self.childNode(withName: "myScoreLabel") as? SKLabelNode {
label.text = "Test" //Must add '.text' otherwise will not compile
}
}

关于ios - 更改从场景编辑器添加的 SKLabelNode 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43417422/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com