Answers:
public static IEnumerator Sequence(params IEnumerator[] sequence)
{
for(int i = 0 ; i < sequence.Length; ++i)
{
while(sequence[i].MoveNext())
yield return sequence[i].Current;
}
}
用法示例:
IEnumerator PrintCoroutine(string arg)
{
yield return new WaitForSeconds(0.3f);
}
StartCoroutine(Sequence(PrintCoroutine("foo"), PrintCoroutine("bar")));
除了什么Heisenbug描述的东西,统一手册没有做出明显的是,你可以yield return
一个Coroutine
对象,你从一个接收StartCoroutine
呼叫。
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);
}
有时这比MoveNext循环更好地阅读,但缺点是您无法阻止子协程通过最顶层协程循环内的逻辑运行,这对于在IEnumerator之上构造更复杂的流控制技术很有用。
有关此的更多信息,您应该查看此Unite视频,该视频介绍了在不构建自己的协程调度程序的情况下从协程中获得更多收益的方法。