【问题标题】:How to I get my text to display my score in Unity?如何让我的文本在 Unity 中显示我的分数?
【发布时间】:2016-09-07 13:10:02
【问题描述】:

我正在编写游戏,我希望文本显示玩家分数,分数会随着时间的推移而增加。但是,它不起作用。为什么它不起作用?

#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 and Scoreboard.Update () (在 Assets/Scripts/Timer and Scoreboard.js:17)

【问题讨论】:

    标签: javascript string text unity3d unityscript


    【解决方案1】:

    我可以看到您已经将名为 Score 的 Text 组件分配给编辑器中的 text 插槽,但是当您在 Start 函数中执行 text = GetComponent(Text); 时覆盖了它。只需删除 text = GetComponent(Text);,您的代码就可以工作了。

    如果你想知道为什么text = GetComponent(Text); 返回null,那是因为没有Text 组件附加到脚本附加到的同一个游戏对象(主摄像头)。 text = GameObject.Find("In-Game UI/Score").GetComponent(Text); 应该可以正常工作。您不必这样做,因为您已经从编辑器分配了Text

    【讨论】:

    • 我去掉了 GetComponent(Text);,它并没有改变任何东西
    • 糟糕,这是另一回事。谢谢!
    猜你喜欢
    • 2021-06-15
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    相关资源
    最近更新 更多