c# - 为什么当前文本没有更新?

标签 c# unity3d

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

enter image description here

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;
    }
}

我现在完全统一了。有什么解决办法吗?

最佳答案

我怀疑您正在使用 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


How do I reassign the livesText?

你可以制作 GameSessionInstance

public static GameSession Instance;

这有点滥用单例模式,有点争议..但我认为这对于快速原型(prototype)制作是没问题的。

并在 YourFirstScript 中制作 levelText

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;
        }
    }
}

关于c# - 为什么当前文本没有更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56795226/

相关文章:

c# - 如何使用 Microsoft.VisualBasic 引用在 MonoDevelop 中使用 IsNumeric 方法?

c# - 读取和写入剪贴板

android - Unity Android 键盘文本在白色背景上显示白色文本

c# - .NET 4.x 相对于 .NET 3.5 更改了小数点 - 如何修复? (统一)

c# - Unity3d Swipe 跳转不是很灵敏

c# - GroupBy 根据条件返回 Count 和 Value

c# - 如何修复 System.Data.SqlClient.SqlException : Login failed for user

c# - 单击 asp 按钮获取下拉列表的值

c# - 我应该在销毁游戏对象时取消字段吗?

c# - 在 C#.net 中处理大量数据表的有效方法