# Coroutines in series

How would i go about stacking up a series of Coroutine calls that should be executed one after the other?

I have tried getting a flashing color effect looping a series of color lerps in a coroutine but its not working.

public static IEnumerator Sequence(params IEnumerator[] sequence)
{
for(int i = 0 ; i < sequence.Length; ++i)
{
while(sequence[i].MoveNext())
yield return sequence[i].Current;
}
}


usage example:

IEnumerator PrintCoroutine(string arg)
{
yield return new WaitForSeconds(0.3f);
}

StartCoroutine(Sequence(PrintCoroutine("foo"), PrintCoroutine("bar")));

• Nice general purpose solution. – demented hedgehog Jul 15 '15 at 4:53

In addition to what Heisenbug described, something that the Unity manual doesn't make obvious is that you can yield return a Coroutine object, which you receive from a StartCoroutine call.

public IEnumerator RunColorCoroutineLoop()
{
while (true) {
yield return StartCoroutine(FirstColorCoroutine());
yield return StartCoroutine(SecondColorCoroutine());
yield return StartCoroutine(ThirdColorCoroutine());
yield return StartCoroutine(FourthColorCoroutine());
}
}

public IEnumerator FirstColorCoroutine()
{
SetColor("color1");
yield return new WaitForSeconds(1f);
}

public IEnumerator SecondColorCoroutine()
{
SetColor("color2");
yield return new WaitForSeconds(1f);
}

public IEnumerator ThirdColorCoroutine()
{
SetColor("color3");
yield return new WaitForSeconds(1f);
}

public IEnumerator FourthColorCoroutine()
{
SetColor("color4");
yield return new WaitForSeconds(1f);
}


This sometimes makes for better reading than a MoveNext loop, but has the disadvantage that you can't prevent the child coroutine from running via logic within the topmost coroutine loop, which could be useful for constructing more sophisticated flow control techniques on top of IEnumerator.

For more on this, you should look at this Unite video which covers getting more out of your coroutines without building your own coroutine scheduler.

• Both (this and below) asnwers are great. I woul go with this approach if you care more about code transparency in traditional OOP. If you however doing data-driven development @Heisenbug solution wll serve you better. – IndieForger May 20 '17 at 10:26