You can stack them, but you have to do it manually. There are several ways this could be done. One is to use a Queue<IEnumerator> and a boolean variable to determine if a coroutine is already running and then either just start a coroutine when none is running at the moment or instead of passing it to StartCoroutine you can store it in the queue. At the end of the coroutine you can check the queue and if it has items, just pop one and start that coroutine. While the overall setup is quite simple, it has some drawbacks. First of all if you want to queue several different coroutines, the starting of the queue coroutines need to be at the end of every coroutine you want to stack. Also starting / queue a coroutine always requires this if-else statement.
Another solution is to use a Queue in combination of a coordinator / director coroutine that is running all the time and that will actually start the coroutines at the right time(s).
Both approaches have one issue: You can not use StopCoroutine to terminate a running coroutine. You could clear the queue which would cancel all queued coroutines but the current one has to finish. If you need to be able to stop the coroutine at any time the first approach would allow this with a few modifications. If not the second one is the simplest one to use.
// Second case:
private Queue<IEnumerator> coroutineQueue = new Queue<IEnumerator> ();
void Start()
{
StartCoroutine(CoroutineCoordinator());
}
IEnumerator CoroutineCoordinator()
{
while (true)
{
while (coroutineQueue.Count >0)
yield return StartCoroutine(coroutineQueue.Dequeue());
yield return null;
}
}
IEnumerator Lerpfunction ()
{
//Lerp implementation
}
With this setup you can simply use
coroutineQueue.Enqueue(LerpFunction());
instead of
StartCoroutine(LerpFunction());
The nice thing is you can queue any kind of coroutine (as long as it is not stopped manually) without any special addition to the coroutine. The “CoroutineCoordinator” will pick up any coroutine that is queued and just start it if he is currently idling. If another coroutine is queued while the coordinator is already running a coroutine, nothing happens. When the first coroutine has finished it automatically starts the next one.
The first case i’ve mentioned would look like this:
// first case
IEnumerator runningCoroutine = null;
private Queue<IEnumerator> coroutineQueue = new Queue<IEnumerator> ();
IEnumerator Lerpfunction()
{
//Lerp implementation
runningCoroutine = null;
if (coroutineQueue.Count > 0)
{
runningCoroutine = coroutineQueue.Dequeue();
StartCoroutine(runningCoroutine);
}
}
To start / queue a coroutine you would do this:
if (runningCoroutine == null)
{
runningCoroutine = LerpFunction();
StartCoroutine(runningCoroutine);
}
else
coroutineQueue.Enqueue(LerpFunction());
To stop all running and queued coroutines you can now do:
coroutineQueue.Clear();
if (runningCoroutine != null)
StopCoroutine(runningCoroutine);