currentYield = routine.Current as YieldInstruction;
return true;
}
// 协程执行完毕
return false;
}
复制代码
自定义调理器: 需要实现StartCoroutine,StopCoroutine和Update函数
// 存储待执行的协程列表
private List<CustomCoroutine> coroutines = new List<CustomCoroutine>();
// 启动一个协程
public CustomCoroutine StartCoroutine(IEnumerator routine)
{
CustomCoroutine coroutine = new CustomCoroutine(routine);
coroutines.Add(coroutine);
return coroutine;
}
// 更新协程调度器,需要在每一帧调用
public void Update()
{
for (int i = coroutines.Count - 1; i >= 0; i--)
{
coroutines[i].MoveNext();
}
}
public void StopCoroutine(CustomCoroutine routine)
{
coroutines.Remove(routine);
}
public void StopAllCoroutine()
{
coroutines.Clear();
}
复制代码
调用:
CustomCoroutineScheduler scheduler = new CustomCoroutineScheduler();
void Start()
{
// 启动一个协程
scheduler.StartCoroutine(TestCoroutine());
}
void Update()
{
scheduler.Update();
}
IEnumerator TestCoroutine()
{
Debug.Log("Coroutine started");
yield return new WaitForFrames(3);
Debug.Log("Waited for 3 frames");
Debug.Log("Coroutine ended");
}
复制代码
结果:
其他有用的链接:
KarnageUnity/CustomCoroutine: Two C# classes demonstrating how Unity implements Coroutines (github.com)
gohbiscuit/UnityCustomCoroutine: Unity Custom Coroutine class can be use to handle multiple or nested coroutine (github.com)
Ellpeck/Coroutine: A simple implementation of Unity's Coroutines to be used for any C# project (github.com)
utamaru/unity3d-extra-yield-instructions:Unity3D 协程的其他自定义 yield 指令 (github.com)