我正在编写一个游戏,我希望文本显示玩家的分数,该分数会随着时间的推移而增加。但是,它不起作用。为什么不起作用?
#pragma strict
import UnityEngine.UI;
var score = 0;
var highScore : int;
var text : Text;
function Start() {
highScore = PlayerPrefs.GetInt("High Score");
text = GetComponent(Text);
text.text = score.ToString();
}
function Update() {
score += Time.deltaTime;
if (score >= highScore) {
highScore = score;
PlayerPrefs.SetInt("High Score", highScore);
}
text.text = score.ToString();
}
我不断收到错误:
NullReferenceException:未将对象引用设置为对象的实例 Timer 和 Scoreboard.Update () (位于 Assets/Scripts/Timer 和 Scoreboard.js:17)
最佳答案
我可以看到您已经将名为 Score 的 Text
组件分配给编辑器中的 text
插槽,但是当您执行 text = GetComponent 时您覆盖了该组件(Text);
在您的 Start 函数中。只需删除 text = GetComponent(Text);
,您的代码就应该可以工作。
如果您想知道为什么 text = GetComponent(Text);
返回 null,那是因为没有 Text
组件附加到同一个 GameObject(Main Camera) ) 脚本已附加到。 text = GameObject.Find("In-Game UI/Score").GetComponent(Text);
应该可以正常工作。您不必执行此操作,因为您已经从编辑器分配了文本
。
关于javascript - 如何让我的文本在 Unity 中显示我的分数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37174391/