How do coroutine interrupts work?

in several places that explained this they say the same thing. The problem is that what I try in my code doesn’t match, and I don’t understand what is happening. examples:


yield return new WaitForSeconds(x) According to what I read, this line makes you wait for x seconds and then the coroutine is restarted ignoring this line


sample code:

public IEnumerator coroutine()
{
          Debug.Log("1");
          Debug.Log("2");
          yield return new WaitForSeconds(3);
          Debug.Log("3");
}

According to what I read, “1” “2” should be printed on the console, wait 3 seconds and then “1” “2” “3” should be printed. but it prints “1” “2” it waits 3 seconds and then it prints “3” and stops.


yield return null according to what I read this line should restart the coroutine without doing anything else


sample code:

public IEnumerator coroutine()
{
          Debug.Log("1");
          Debug.Log("2");
          yield return null;
          Debug.Log("3");
}

Here the same thing is supposed to automatically print “1” “2” “1” “2” “3” but “1” “2” “3” is printed directly, causing said line to do practically nothing.


So I don’t understand what is happening. What am I doing or misunderstanding? Is it outdated information that I read? Did the articles I read omit to say that these interrupts work differently in different situations?

Hey there,

thank you for the detailed description of your problem.

What you provide is the expected behaviour and your understanding of how coroutines work is just not correct.
The first example will print “1” “2” and then WaitFor 3 Seconds. Then it will resume the code at the position it was paused. It will not restart the function.

yield return null does the exact same thing - only that the wait time is so small that you do not notice that it even waited. It will simply wait until the next frame.

You should be able to test this with the following code:

  public void Start() {
        StartCoroutine(coroutine());
        print("2.5f");
  }

This should print “1”, “2”, “2.5” and then “3” immediatly.

Let me know if that helped and explaines the issue or if there are any open questions.

ok, so what i read was wrong. Thanks a lot.

Another question then: if I want to stop a coroutine in the middle and restart it, is there any code for that or do I have to call a void that has a stopCoroutine and a startCoroutine?