Lesson 92. Using Coroutines
1. What is a Coroutine?
What is a Coroutine?
定義: A method which can suspend ( otherwise known as yield ) its execution until the yield instructions you gave it are met.
( So yield is another way of saying give back or relinquish or suspend.)
用處: A useful approach for us to allow our game to wait for something to happen or to not continue until some other conditions are met.
例如:當玩家血歸0,call KillPlayer coroutine (執行以下動作):
-
Trigger the death animation
-
Yield (wait) for three seconds.
-
Restart the level.
如果沒有Yield 會馬上Restart the level。
如何使用:
1. Startcoroutine(NameofCoroutine()) : call Coroutine的方法
2.
IEnumerator NameOfCoroutine()
{
//A thing to do
yield return SomeCondition // yield return until something is met
//B thing to do
}
IEnumerator 像是 void、int 是一種 return type。
SomeCondition : 可以用 new WaitForSconds(3);
流程: 執行A(yield return 前的敘述) -> 等條件發生 -> 執行B(yield return 後的敘述)
停止方式:
Coroutine firingCoroutine;
firingCoroutine = StartCoroutine(FireContinuously());
//方法一
StopAllCoroutines();
//方法二
StopCoroutine(firingCoroutine);
哪時可以用?
1. 需要等一段時間後才發生的事。例如:Laser Defender 的連續發射的間隔時間。
詳細作法連結