Call nested coroutines without yielding?

Hello there,

I have a very CPU-heavy task that is happening pretty much all the time. This task is to create a mesh “trail” behind a moving object. At first, I just dropped pieces of mesh every frame after the object moved a certain distance. This worked great and was simple but as the mesh got more complex it became clear that we would want the distance between “chunks” to be set and variable.

This means that instead of drawing one chunk every frame, the system waits until the object has moved “far enough” and draws the section in between. On the other end of things, if the object is moving very fast and the mesh is very detailed, sometimes the system has to draw a few sections from one frame to another in order to “catch up.”

What I’m trying to do now I have done for two reasons. What I did was to turn many of the involved functions into IEnumerators in order to “break up” the process and give me the control to “step through” the creation process triangle by triangle within Unity. This has helped greatly in debugging the system; that’s reason one. Reason two has to do with performance. I might be wrong to think this way, but in the case where I go a few frames between laying down a new section, it might make sense to spread that load out over all those frames, rather than drawing every triangle as soon as the object has gone far enough. Either way, I’m sure that both cases will be in play since the mesh draws itself at varying levels of detail, some with small sections, some with large sections.

Anyway, this change has essentially “slowed down” the process to the point that it will never be able to “catch up” since it can only draw one triangle per frame. Even if I remove the “yield” within the “add triangle” function, I still end up waiting a frame after each time that I call

yield return StartCoroutine(Function());

which, from my understanding, is required when you are “nesting” coroutine calls. That means in this case that each time I call the function that draws a set of triangles, the function doesn’t resume until the next frame. If I need to draw many sections per frame, it seems that I have to turn the function back into a “void.” Is there any way around this? What I would like to happen is for a set of function calls to essentially “bubble up” yields so that I can break up the execution at any point, but I don’t have to just because I’m pushing the stack.

Any ideas?

How Coroutines really work

All you need is:

foreach(var e in Function())
   yield return e;

This doesn’t seem to work in C#. To I need to change the return of the function? It says it doesn’t have a “GetEnumerator()” function

Huh. Turned it into an IEnumerable and it worked great. THANKS!

Oops. Yeah, my bad - for IEnumerator functions it’s:

var e = Function();
while(e.MoveNext())
   yield return e.Current;

So, for clarity…

How does Unity’s internal engine handle a simple StartCoroutine() call? I have some that appear to keep running after their first yield statement, but others that won’t. Is StartCoroutine really fire-and-forget, or do you have to use yield return StartCoroutine() from the calling method?

StartCoroutine does what it says, it starts the coroutine.

yield return StartCoroutine also does what it says, it starts the co-routine and waits for it to finish before proceeding.

I just posted two quick snippets to show how IEnumerables/IEnumerators work under the hood:

http://pastebin.com/tjSebJQc
http://pastebin.com/QiJV29yW

Combined with super pigs stuff, it’s really quite elementary.

What’s not elementary is LINQ, but I’ll do that later :stuck_out_tongue:

I understand that much, but why does the coroutine continue with StartCoroutine() in some cases and stop on its first yield in others?
What causes the coroutine to continue to its end?

Ok, solved my own problem. Turns out the object that calls the StartCoroutine cannot be destroyed in the next frame, or the called coroutine will never get past the first yield statement. I guess the coroutine is tied to the caller. Once I switched the caller to a persistent GO, it worked perfectly.

Most people seem to confuse coroutine with threads. Coroutines are not threads/background worker. StartCorotuine (simply said) puts the Coroutine (which is in fact an IEnumerator) in some kind of list/queue which is called on each frame and is tied to the MonoBehaviour calling it.

When the MonoBehaviour gets destroyed, all coroutines stop working because the MonoBehaviour class can’t advance them to the “next iteration”. That being said, you could run the Coroutine in the context of a different MonoBehaviour, though this may like cause errors or memory leaks if you require variables from the MonoBehaviour were the original method was declared.

Also. A Coroutine/IEnumerator starts on the first call of MoveNext() (which is done by the StartCoroutine/MonoBehaviour internally) until the end of the Method or until yield return break; is called

public IEnumerator SomeCoroutine() {
    // do something
    yield return null; // wait till next frame
    // do more
    ...
    if(/*expression*/) {
        // prematurely exist the iteration/IEnumerator/Coroutine
        yield return break; 

        // the code below will never be executed if the expression is true
    }
   
   yield return null; // Wait for another frame
   // end reached, coroutine stops 
}