簡體   English   中英

達到零后無法使計時器循環

[英]Unable to make timer loop after hitting zero

我正在使用一個從設定的數字開始倒數的計時器,當它達到零時,它應該休息一下並重新開始。

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

我遇到的問題是使計時器循環。 發送“計時器重置”消息后,它將不再運行計時器。

我建議將邏輯簡化為以下形式:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM