最有效的優化是**根本不執行不必要的程式碼**。Unity 每幀自動呼叫 Update、FixedUpdate,若在其中執行昂貴邏輯(物理檢測、路徑規劃、大量數學運算)會嚴重拖垮幀率。本文介紹三種「按需啟用」模式與協同程式分時執行技巧。
void Update() {
if (Vector3.Distance(transform.position, target.position) > 100) return;
// 執行昂貴 AI 邏輯...
}
缺點:Update 仍被呼叫,距離計算本身就有開銷;物件不可見時仍佔用 CPU。
void OnBecameVisible() { enabled = true; }
void OnBecameInvisible() { enabled = false; }
void OnTriggerEnter(Collider other) {
if (other.CompareTag("Player")) enabled = true;
}
void OnTriggerExit(Collider other) {
if (other.CompareTag("Player")) enabled = false;
}
Rigidbody (IsKinematic) + Collider (IsTrigger)。協同程式允許函數**暫停執行**並在未來某幀/秒數後繼續,不阻塞主執行緒。
IEnumerator MyCoroutine() {
DoSomething();
yield return null; // 等待下一幀
DoSomethingElse();
}
IEnumerator WaitTwoSeconds() {
DoSomething();
yield return new WaitForSeconds(2f); // 等待 2 秒
DoSomethingElse();
}
// 串聯協同程式
IEnumerator Chain() {
yield return StartCoroutine(WaitTwoSeconds());
Debug.Log("WaitTwoSeconds 完成後才執行這行");
}
void Start() {
StartCoroutine(MyCoroutine()); // 啟動協同程式
}
IEnumerator AIDecisionLoop() {
while (true) {
if (Vector3.Distance(transform.position, player.position) < 50f) {
// 玩家接近才執行昂貴決策
RunExpensiveAILogic();
}
yield return new WaitForSeconds(5f); // 每 5 秒檢查一次
}
}
| 特性 | Update | Coroutine |
|---|---|---|
| 呼叫頻率 | 每幀 (60+ Hz) | 自訂 (yield return null = 下一幀; WaitForSeconds = 秒級) |
| 狀態保持 | 需靠成員變數 | 局部變數自動保持(狀態機) |
| 可讀性 | 分散在多幀 | 線性寫法,邏輯集中 |
| 除錯 | 難中斷點 | 可在 yield 處中斷 |
Unity 不允許在 Update/FixedUpdate 直接 yield,必須另寫 IEnumerator 方法並用 StartCoroutine 啟動。
enabled = false / GameObject.SetActive(false)。WaitForSeconds。OnBecameVisible。yield return null 分攤負載。