如何在 Unity C# 中使用协程制作计时器

问题描述 投票:0回答:1

我正在尝试使用协程为我的游戏制作 2 分钟计时器。它从游戏的开始开始倒计时。一切正常,直到达到 1 分钟。在那之后出了问题(我想错误是在

yield
命令中,因为当我调试代码时,它会抛出那一行)。

错误:
有指向显示错误的 GIF 链接的链接: https://giphy.com/gifs/Pk8t1StrR8dmip30NN

private int seconds;
private int minutes = 1;

void Start()
{
    seconds = 59;
    timer.text = "2:00";
    StartCoroutine(CountSeconds());
}

IEnumerator CountSeconds() 
{
    while (true)
    {

        seconds--;

        if (seconds >= 10)
        {
            timer.text = $"{minutes} : {seconds}";
        }
        else 
        {
            timer.text = $"{minutes} : 0{seconds}";

            if (seconds == 0)
            {
                seconds = 59;
                minutes--;
            }
        }

        yield return new WaitForSeconds(1f);
    }
}

}

请帮我解决这个荒谬的问题

c# unity3d
1个回答
0
投票

我会以不同的方式处理它并使用 TimeSpan 来倒计时分钟,因为它会使一切变得更容易。

private TimeSpan timeLeft = new TimeSpan(0, 2, 0);

void Start()
{
    timer.text = timeLeft.ToString("mm\:ss");
    StartCoroutine(CountSeconds());
}

IEnumerator CountSeconds() 
{
    while (true)
    {
        //I am reducing the time left on the counter by 1 second each time.
        timeLeft = timeLeft.Subtract(new TimeSpan(0, 0, 1));
        timer.text = timeLeft.ToString("mm\:ss");

        yield return new WaitForSeconds(1f);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.