How to properly restart a coroutine?

I have a coroutine which works as my countdown timer. It starts with 90 seconds and goes down to 0 seconds. On keypress I want it to be restored back to 90 seconds again and start again. However, if say the timer shows 47 seconds and I stop the the coroutine, then start it again, the coroutine just goes on from 47, rather than returning back to 90. Why is that? How can I properly reset it? I’m using for() loops in it, so maybe the values in the loop aren’t reset?

As far as i know, coroutines start off just where they stopped.

Eg:

IEnumerator MyCoroutine ()
		{
                  int test1;
                  int test2; //<-- Lets assume the machine is here as you stop the function, it will
                  int test3;// start here as you continue.
                  int test4;
                  int test5;

                  yield retun null;
                }

Coroutine basics-video: Coroutines - Unity Official Tutorials - YouTube (WATCH IT :slight_smile: ! )

Personally, i would solve your problem in perticular also with for loops:

public int countValue = 90; //For example... 
int counter;

IEnumerator CountDown ()
         {
            counter = 0;

            for(counter; i != countValue; i++ )//Loop that gets executed 90 times.
             {
               yield return new WaitForSeconds(1);
             }
            yield return null; //Done
}

public void resetCounter() //Resets the counter variable, so you don't actually have to stop the coroutine ;-) (I guess...^^).
{
  counter = 90;
}

I assume, that the only solution here is to store the counter variable outside of the coroutine, because if it was not, it would probaply also not be reset.

The proper name for “StopCoroutine()” , should maybe be “PauseCoroutine()”…^^

I hope i could help you :slight_smile:
Good luck finishing your project! Never give up, there’s always a way!
-Toonk

As StopCoroutine is more like a Pause as coroutine will start as they wher stopted I called the start using a variable that I init every time :

    private IEnumerator myCoroutine;

    protected override void Awake() {
        myCoroutine = MyCoroutine();
    }

    public void CoroutineReset() {
        StopCoroutine(myCoroutine);
        myCoroutine = MyCoroutine();
        StartCoroutine(myCoroutine);
    }

    private IEnumerator MyCoroutine() {
        Debug.Log("start");
        yield return new WaitForSeconds(1f);
        Debug.Log("start");
    }