达到零后无法使计时器循环

时间:2019-05-22 19:06:06

标签: c# unity3d timer

我正在使用一个从设定的数字开始倒数的计时器,当它达到零时,它应该休息一下并重新开始。

private int timer;
public int duration;

private bool timerRunning = true;

void Start()
{
    StartCoroutine("TimeDown");

    timer = duration;
}

void Update()
{

    if (timer <= 0f)
    {
        timer = duration;

        Debug.Log("Timer Reset");

        timerRunning = false;

    }

    if (timerRunning == false)
    {
        StartCoroutine("TimeDown");

        timerRunning = true;
    }


    Debug.Log("Timer: " +timer);
}

IEnumerator TimeDown()
{
    while (true)
    {
        yield return new WaitForSeconds(1);
        timer--;
    }
}

我遇到的问题是使计时器循环。发送“计时器重置”消息后,它将不再运行计时器。

1 个答案:

答案 0 :(得分:4)

我建议将您的逻辑简化为以下形式:

private int timer;
public int duration;

void Start()
{
    timer = duration;
    StartCoroutine(TimeDown());
}

void Update()
{
    // Nothing is needed each frame so Update() should be removed
}

IEnumerator TimeDown()
{
    while (true)
    {
        if (timer <= 0)
            timer = duration;

        yield return new WaitForSeconds(1);

        timer--;
        Debug.Log("Timer: " + timer);
    }
}

还要确保在检查器中设置了duration