Is Coroutine yield order affected by Script Execution Order?

Unity will delegate Update() calls on all MonoBehaviours based on the configurable script execution order. Is this true for Coroutines?

For example, if my execution order specifies the Character MonoBehaviour before the Enemy MonoBehaviour, but Enemy launches a looping coroutine before Character launches a looping coroutine, which should I expect between the following?

  1. Character’s Coroutine yields before Enemy’s each frame because of the script execution order
  2. Enemy’s Coroutine yields before Character’s each frame because Enemy’s was started first

Following fafase’s advice, I went ahead and tested it out myself.

A was set to run before B in execution order, but B launched a coroutine before A launched a coroutine (triggered by key presses).

The result was:

  1. A.Update()
  2. B.Update()
  3. A.Coroutine()
  4. B.Coroutine()

And, of course, during the period between when I pressed the trigger for B and A, the result was

  1. A.Update()
  2. B.Update()
  3. B.Coroutine()

According to this handy manual page, coroutines are executed right after the Update function for that Monobehaviour.

As a side note, just because an IEnumerator function is written within a particular Monobehaviour doesn’t mean that the coroutine needs to be run on that particular Monobehaviour. You can call StartCoroutine(MyCoroutine()), or you can also do someOtherMonobehaviour.StartCoroutine(MyCoroutine()). The execution order would be used for whichever Monobehaviour you start the coroutine with.

In fact, I occasionally use a Monobehaviour who’s only responsibility is to run coroutine functions for non-Monobehaviour classes…

Hi there,

I had the same question an did some additional testing. The answer is:

First ALL Update routines are run in the defined execution order.
Second ALL Coroutines are run in the defined execution order.

So the pattern is:

Update1()

Update2()

Update3()

Coroutine1()

Coroutine2()

Coroutine3()

So, if you want that your coroutine runs directly after the update routine there is a little trick. To get the execution pattern:

Update1()

Coroutine1()

Update2()

Coroutine2()

Update3()

Coroutine3()

try this code. It works, I tested it.

void Start () {
        _Enumerator = MyCoroutine();
	}

	void Update () {
        //See IEnumerator for return values and
        //evaluate them.
        _Enumerator.MoveNext();
	}

    private IEnumerator _Enumerator = null;

    private IEnumerator MyCoroutine()
    {
        while(true)
        {
            //Your coroutine code here
            yield return null;
        }
    }

Of course, by using this trick, you don’t have a real coroutine, but it works. :slight_smile: