1. 協同程序 (Coroutine) 簡介
協同程序是 Unity 中一種特殊的功能,允許你暫停函式的執行並在之後的幀中繼續。這對於需要在多個幀之間分散執行的操作特別有用。
2. 協同程序的主要用途
- 實現延遲執行
- 在幀之間分散耗時操作
- 創建定時事件
- 管理複雜的動畫序列
3. 使用協同程序的步驟
- 引用系統集合命名空間 (System.Collections)
- 定義一個方法並且返回 IEnumerator
- 在方法內使用 yield return 語句
- 使用 StartCoroutine 啟動協同程序
4. 協同程序的語法
using System.Collections;
using UnityEngine;
public class ExampleClass : MonoBehaviour
{
private IEnumerator ExampleCoroutine()
{
Debug.Log("協同程序開始");
yield return new WaitForSeconds(2f);
Debug.Log("等待 2 秒後繼續執行");
}
void Start()
{
StartCoroutine(ExampleCoroutine());
}
}
5. yield 語句的類型
- yield return null:等待下一幀
- yield return new WaitForSeconds(float):等待指定的秒數
- yield return new WaitForSecondsRealtime(float):等待指定的真實時間(不受 Time.timeScale 影響)
- yield return new WaitUntil(Func<bool>):等待直到條件為真
- yield return new WaitWhile(Func<bool>):等待直到條件為假