首页 > 解决方案 > 为什么当前文本没有更新?

问题描述

我正在尝试在我的游戏中创建一个生命系统,但屏幕上的测试没有更新,尽管变量是。我希望我的文字也能更新。

在此处输入图像描述

LoseCollider 类

[SerializeField] TextMeshProUGUI livesText;
[SerializeField] static int currentLives = 4;

public void Start()
{
    livesText.text = "Lives: " + currentLives.ToString();
    Debug.Log(currentLives);
}

private void OnTriggerEnter2D(Collider2D collision)
{
    if (currentLives > 0)
    {
        currentLives--;
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }

    if (currentLives <= 0)
    {
        SceneManager.LoadScene("Game Over");
        currentLives = 4;
    }
}

我认为你对 DontDestroy 是正确的问题。

它来自另一个脚本

public class GameSession : MonoBehaviour
{

    // config params
    [Range(0.1f, 10f)] [SerializeField] float gameSpeed = 1f;
    [SerializeField] int pointsPerBlockDestroyed = 83;
    [SerializeField] TextMeshProUGUI scoreText;
    [SerializeField] bool isAutoPlayEnabled;


    // state variables
    [SerializeField] int currentScore = 0;


    private void Awake()
    {
        int gameStatusCount = FindObjectsOfType<GameSession>().Length;

        if (gameStatusCount > 1)
        {
            gameObject.SetActive(false);
            Destroy(gameObject);
        }
        else
        {
            DontDestroyOnLoad(gameObject);
        }
    }


    // Start is called before the first frame update
    void Start()
    {
        scoreText.text = currentScore.ToString();  

    }

    // Update is called once per frame
    void Update()
    {
        Time.timeScale = gameSpeed;
    }

    public void AddToScore()
    {
        currentScore += pointsPerBlockDestroyed;
        scoreText.text = currentScore.ToString();
    }

    public void ResetGame()
    {
        Destroy(gameObject);
    }

    public bool IsAutoPlayEnabled()
    {
        return isAutoPlayEnabled;
    }
}

我现在完全合一了。任何想法如何解决这个问题?

标签: c#unity3d

解决方案


正如我怀疑你正在使用DontDestroyOnLoad.

您的第一个脚本似乎附加到与其下方的层次结构相同的对象GameSession或位于其下的层次结构中(一个孩子)。

这使得再也不会Start被调用。


但是您可以注册一个回调SceneManager.sceneLoaded来更新文本:

public class GameSession : MonoBehaviour
{
    // ...

    private YourFirstScript yourFirstScript;

    // rather implement a Singleton pattern this way
    private static GameSession Instance;

    private void Awake()
    {
        if(Instance)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;

        DontDestroyOnLoad(gameObject);

        // Add the callback
        // it is save to remove even if not added yet
        // this makes sure a callback is always added only once
        SceneManager.sceneLoaded -= OnSceneLoaded;
        SceneManager.sceneLoaded += OnSceneLoaded;

        yourFirstScript = GetComponentInChildren<YourFirstScript>(true);
    }

    private void OnDestroy()
    {
        // make sure to remove callbacks when not needed anymore
        SceneManager.sceneLoaded -= OnSceneLoaded;
    }

    // called everytime a scene was loaded
    private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        scoreText.text = currentScore.ToString(); 

        // Since you made it public anyway simply call the method
        // of your first script
        // You shouldn't call it Start anymore
        // because now it will be called twice
        yourFirstScript.Start();
    }

    // ...
}

注意:在场景加载后livesText也可以DontDestroyOnLoad重新分配或者重新分配也很重要。NullReferenceException否则无论如何你都会得到一个。


如何重新分配livesText

你可以InstanceGameSession

public static GameSession Instance;

这有点滥用单例模式和一种争议......但我认为这对于快速原型设计来说是可以的。

并且还levelText使YourFirstScript

public TextMeshProUGUI levelText;

然后你可以简单地在相应的levelText对象上有一个新组件,比如

[RequireComponent(typeof(TextMeshProUGUI))]
public class LevelTextAssigner : MonoBehaviour
{
    // you can reference this already in the Inspector
    // then you don't need to use GetComponent
    [SerializeField] private TextMeshProUGUI _text;

    // Is called before sceneLoaded is called
    private void Awake()
    {
        if(!_text) _text = GetComponent<TextMeshProUGUI>();

        // It is possible that the first time GameSession.Instance is not set yet
        // We can ignore that because in this case the reference still exists anyway
        if(GameSession.Instance)
        {
            GameSession.Instance.YourFirstScript.leveltext = _text;
        }
    }
}

推荐阅读