协同路由使这种基于延迟的逻辑非常简单:
void SomeFunction() {
StartCoroutine(WaitThenDoTheThing());
}
IEnumerator WaitThenDoTheThing() {
yield return new WaitForSeconds(NUM_SECONDS);
TheThing();
}
如果你出于任何原因需要打断,
StartCoroutine
将返回一个
Coroutine
对象,然后您可以保留对该对象的引用并用其终止
StopCoroutine(coroutineObject)
:
Coroutine routine;
void SomeFunction() {
routine = StartCoroutine(WaitThenDoTheThing());
}
IEnumerator WaitThenDoTheThing() {
yield return new WaitForSeconds(NUM_SECONDS);
TheThing();
}
void KillCoroutine() {
if (routine != null) {
StopCoroutine(routine);
}
}