User control when a coroutine is resumed?

First of all, this is my first post on the forum and let me say to the Unity team, what a great product!

Now I’m guessing from all my reading that in Unity all coroutines are coded to resume every frame. But I still want to ask because this stops me from writing a simple state machine illustrated below. Is there any way a coroutine is resumed ONLY when I tell it to?

Example:

function StateMachine()
{
    SetStateToLogin();
    yield;

    SetStateToPlay();
    yield;

    SetStateToQuit();
    yield;
}

and in my game code, I can simply say:

var s = new StateMachine();
s.Advance();

... handles login

s.Advance();

.... handles play

s.Advance();

.... handles quitting

Is there anything in UnityScript that would simulate this? I know I can write an state machine class/object or just keep track of a number of state variables and mimic this behaviour, but it just isn’t as elegant.

That depends when you want it to resume - based on time or a check?

function MyCoroutine ()
{
    Debug.Log ("Waiting for condition");

    while (holdExecution) yield;
        // The coroutine will remain on this line till holdExecution is false

    Debug.Log ("Waiting for timeout");

    yield WaitForSeconds (delay);
        // The coroutine will remain on this line till delay seconds has passed

    Debug.Log ("Done!");
}

Thanks for the reply. But the code you provided is still resumed on every frame.

The pattern I described is such that I need external control of when to resume a coroutine (i.e.: outside of the coroutine itself).

I illustrated this with the original code sample.

Note that the coroutine “StateMachine” is ONLY resumed when I call “Advance”, and NOT on every frame.

Come to think of it, internally I think all coroutines gets called “MoveNext()” on every frame correct?

This concept actually isn’t new. For example, in Python, the generator object and now coroutines are only resumed when you call “coroutine.next()”. Granted, Python doesn’t have a main loop to manage like Unity does. But still, it would be uber-cool to allow this flexibility and it would maximize the benefit of a coroutine to the programmer.

It may be helpful to add a generic coroutine that isn’t automatically resumed every frame that users can control within their own scope.

Yes it resumes every frame to check it’s condition. Considering we’re writing a game though, a main loop with a single boolean check should not be a concern performance wise.

Setting it up for external control can easily be achieved by making the conditional yields check on some variable(s) modified by your continue methods.

Your alternative is to implement your own C# coroutines. There should be some examples out there.

Notice though that Unity coroutines are implemented engine level and it is unlikely that you would gain equal performance from a homegrown coroutine system running in parallel in managed code.