以编程方式更改文本以统一显示游戏屏幕上的得分

时间:2017-02-16 07:56:15

标签: c# unity3d

我一直致力于一个简单的2D游戏,它只有三个场景,即开始场景,游戏场景和场景游戏。我想在屏幕上显示游戏中的游戏分数。我在游戏场景中创建了一个得分管理器游戏对象,它使用DontDestroyOnLoad()函数将其传递到屏幕上的游戏中,并且让它访问由游戏管理器管理的得分。我一直在调试我的代码,分数被翻译成分数管理器,并在游戏结束时加载,但由于某种原因,它不会让我更新分数文本对象。这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ScoreManager : MonoBehaviour {

    public static ScoreManager Instance;

    private GameController gameController;

    private int scoreInstance;

    private Text scoreText;

    // When scene is first loaded
    void Awake() {

        this.InstantiateController();

    }

    // Use this for initialization
    void Start () {

        GameObject gameControllerObject = GameObject.FindWithTag("GameController");

        if (gameControllerObject != null)
        {
            gameController = gameControllerObject.GetComponent<GameController>();
        }

        GameObject scoreTextObject = GameObject.FindWithTag("ScoreText");

        if (scoreTextObject != null)
        {
            scoreText = scoreTextObject.GetComponent<Text>();
        }

        scoreInstance = 0;

        scoreText.text = "";

    }

    // Update is called once per frame
    void Update () {

        scoreInstance = gameController.score;
        Debug.Log("Score: " + scoreInstance.ToString());

        scoreText.text = scoreInstance.ToString();

    }

    private void InstantiateController ()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(this);
        }
        else if (this != Instance)
        {
            Destroy(this.gameObject);
        }
    }
}

所以我尝试以编程方式在开始函数中收集“得分文本”ui组件,因为我认为我不能将其公开并拖入文本组件,因为得分管理器实际上处于与得分不同的场景中文本对象。我还尝试添加这一整段代码来将文本组件收集到更新功能中,这样当分数管理器实际上是游戏屏幕的一部分时它就可以这样做。似乎没有什么工作,我不知道为什么。有人可以帮帮我吗?此外,我不断收到“NullReferenceException:对象引用未设置为对象的实例”错误。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

Unity Start功能仅在第一次启用脚本时调用,即不是每次为DontDestroyOnLoad对象更改场景时都会调用。

因此,如果您需要在场景更改后连接一些更改,则需要检测场景更改,或者让在该场景中启动的对象触发您要运行的代码。

在新场景上有另一个对象触发事物很容易且非常简单,但是有一个内置函数可以添加到其他对象中:

void OnLevelWasLoaded(int currentLevel)
{
}

这将在级别更改时调用,并为您提供级别的编号(不是可悲的名字)。但是,上面的内容已被弃用,他们希望您使用Unity的SceneManager,因此现在正确的设置方法是:

Unity 5 OnLevelWasLoaded?

Start()
{
    SceneManager.sceneLoaded += this.OnLoadCallback;
}

void OnLoadCallback(Scene scene, LoadSceneMode sceneMode)
{
    // you can query the name of the loaded scene here
}