Proper way to stop coroutine?

Coroutines are an IEnumerator object. They have their own internal state. It’s different from just calling InvokeRepeating(), which would restart a fresh function call each time.

Here is ALL you need to know about coroutines in Unity:

  1. they are an IEnumerator, also known in some languages as a Generator. It is an object with a .MoveNext() method on it that “yields” the next thing with each subsequent call. That is what you create by calling an IEnumerator: you create the object, you do NOTHING with it, i.e., NONE of your code is actually executed.

  2. calling StartCoroutine() with that object causes Unity to IMMEDIATELY call the .MoveNext() method on that object, which runs until the first yield, which returns something. Unity does this first step BEFORE returning from StartCoroutine().

  3. By Unity’s convention based on what your object returns each time, Unity decides whether and when to ever call .MoveNext() again: wait a bit, wait one frame, never call again, etc.

That’s it. Done. There is literally NOTHING more to coroutines than that.

3 Likes