Search code examples
c#unity-game-enginetimer

Unable to make timer loop after hitting zero


I'm working on a timer that counts down from a set number and when it reaches zero, it should rest back and start again.

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

The issue I am getting is getting the timer to loop. Once it sends the "Timer Reset" message it no longer runs the timer anymore.


Solution

  • I suggest massively simplifying your logic to something like this:

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

    And also make sure that duration is set in the inspector.