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.
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It only takes a minute to sign up.
Sign up to join this communityHow 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")));
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.