Coroutine, Start() and Update() execution order

Hi, I’m newbie in unity programming, here is one simple test program I wrote which I got a bit confusing on the execution orders:

   public float startbegintime = 0;
   public float startendtime =0 ;
   public float updatestarttime = 0;

  public int commonvar = 0;
  public int updatecnt =0;

void Start() {
	
	Debug.Log("Start begin");

	startbegintime = Time.time;
	StartCoroutine(myFunc());
	startendtime = Time.time;

	Debug.Log("Start end");
}


IEnumerator myFunc()
{
	for(int i = 0; i<100; i++)
	{
		Debug.Log("myFunc Loop "+(i+1).ToString());	
		commonvar++;
		
		yield return 0;
	}		
}

void Update () {
	
	if(updatestarttime == 0)
	{
		updatestarttime= Time.time;
		Debug.Log("Update started");
	}
	
	if(updatecnt<100)
	{
		commonvar++;
		updatecnt++;
		Debug.Log("Common var is "+commonvar.ToString());
	}
}

Well, the console output is as follows:

 Start begin
 myFunc Loop 1
 Start end
 Update started
 Common var is 2
 Common var is 3
 myFunc Loop 2
 Common var is 5
 myFunc Loop 3
 Common var is 7
 myFunc Loop 4
......

and the time variables values are startbegintime = startendtime = 0, updatestarttime =0.2

so by the output, I noticed that the execution order is like this:

Start begin → first iteration of coroutine → Start end → first update → second update → second iteration of coroutine → third update → third iteration of coroutine ->…

So why is that there’re 2 consecutive update call before the second iteration of coroutine?

I took a look at the documentation on execution order, seems I still can’t make it clear.
http://unity3d.com/support/documentation/Manual/Execution%20Order.html

which says:

Normal coroutine updates are run after
the Update function returns.

Anybody has some ideas on this? Thanks!

Coroutines run every frame after update - but the primary rule here is that it is running once every frame.

On the first frame the coroutine runs because you tell it to - in Start, which is before Update - it will not run again on that frame. Then afterwards it runs in its normal position after Update.

If you want it to start after the first Update then either:

  • Start it in Update the first time
  • Ignore the first time it is called before update by the first line of it being yield return 0 - in this case Update will be called twice before the main body of the coroutine runs