"yield return StartCoroutine" in Start function

Consider the following code from Unity’s plugin sample code:

IEnumerator Start () 
{	
    CreateTextureAndPassToPlugin();

    yield return StartCoroutine("CallPluginAtEndOfFrames");
}

private IEnumerator CallPluginAtEndOfFrames()
{
    while (true) 
    {		
        // Wait until all frame rendering is done	
        yield return new WaitForEndOfFrame();

        // Set time for the plugin
        SetTimeFromUnity (Time.timeSinceLevelLoad);

        // Issue a plugin event with arbitrary integer identifier.
        // The plugin can distinguish between different			
        // things it needs to do based on this ID.
        // For our simple plugin, it does not matter which ID we pass here.
        GL.IssuePluginEvent (1);
    }
}

Question:

Why put the “yield return” before “StartCoroutine” in the Start() function?

The function “CallPluginAtEndOfFrames” seems like it will never return. So, it seems like the “yield return” in the Start() function will needlessly prevent the Start() function from returning normally.

From http://docs.unity3d.com/Manual/ExecutionOrder.html :

“[…] yield StartCoroutine Chains the
coroutine, and will wait for the
MyFunc coroutine to complete first.”

Hello. I’m not sure in this but I think the coroutines work other way than the normal functions. You make a coroutine to run asynchronously from your game so it won’t “pause” the running game. I think it works on a lifecycle like this:

  • it runs for some frame and prepares
    for stop
  • saves the current state of the
    coroutine
  • after it gets processor clocktime
    again it loads the state and
    continues where it stopped

The code above returns again and again after some frames with: yield return new WaitForEndOfFrame();. So the CallPluginAtEndOfFrames returns and that’s why the Startcoroutine can return too.

By the way the infinite loop is good. Imagine if you want to make an endless runner which only end when the main character dies. When the character dies, the gameobject with the script will die too so infinite loop over :slight_smile: