Stopping an IEnumerator Function

Is it possible to stop an IEnumerator in the middle of its execution? It seems like once its begun, its going to continue until its parameters have been fulfilled.

It depends of what you do with it.

You can stop it if you start it with a string parameter like this :

StartCoroutine( "DoAction" );
StopCoroutine( "DoAction" );

if you do this :

StartCoroutine( DoAction() );

you can’t.

After all this consideration, you can try to use this :

http://whydoidoit.com/documentation/html/class_radical_routine.html

I used it and it works great !

If your coroutine has some kind of loop in it, then you can check a condition and decide if you want to yield again or to end the loop. Example:

bool gameOver = false;
IEnumerator Count() {
 
    for(int i = 0; i <= 100; ++i)
    {
    Debug.Log("i is" + i);

    if(gameOver)
       yield break;
    else
       yield return new WaitForSeconds(1);
    }
}

If anyone outside the coroutine sets gameOver to true, the coroutine will stop running.
That could also be rewritten as a while loop.

You could use a similar method with a counter to prevent the same coroutine from running twice; starting a new one would end the old one, like so:

int lastRunner = 0;
IEnumerator SingleRunner() {

    int myNumber = ++lastRunner;

    for(int i = 0; i <= 100; ++i)
    {
    Debug.Log("i is" + i);

    if(myNumber == lastRunner)
       yield return new WaitForSeconds(1);
    else
       yield break;
    }
}

Each time SingleRunner is started the runner gets a new number, and any old runners will check their numbers and then bail out.

You could make the lastRunner variable static if you only want one running for the whole class, instead of one per instance.