萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Unity3D 效能優化核心原則:不需要時不要呼叫函式

Unity3D 效能優化黃金法則:少做工、延遲做、分散做

最有效的優化是**根本不執行不必要的程式碼**。Unity 每幀自動呼叫 Update、FixedUpdate,若在其中執行昂貴邏輯(物理檢測、路徑規劃、大量數學運算)會嚴重拖垮幀率。本文介紹三種「按需啟用」模式與協同程式分時執行技巧。

反模式:每幀檢查距離

void Update() {
    if (Vector3.Distance(transform.position, target.position) > 100) return;
    // 執行昂貴 AI 邏輯...
}

缺點:Update 仍被呼叫,距離計算本身就有開銷;物件不可見時仍佔用 CPU。

模式一:OnBecameVisible / OnBecameInvisible(渲染器可見性)

void OnBecameVisible()  { enabled = true;  }
void OnBecameInvisible() { enabled = false; }
  • 優點:零成本,由渲染管線自動驅動。
  • 缺點:任何相機(含場景編輯器相機)可見即啟用,可能誤觸發;不適合純邏輯實體(無渲染器)。

模式二:Trigger 碰撞體偵測玩家進出

void OnTriggerEnter(Collider other) {
    if (other.CompareTag("Player")) enabled = true;
}
void OnTriggerExit(Collider other) {
    if (other.CompareTag("Player")) enabled = false;
}
  • 優點:精確控制「玩家接近」語意,適合 AI、互動物件。
  • 需求:掛載 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()); // 啟動協同程式
}

AI 低頻決策範例

IEnumerator AIDecisionLoop() {
    while (true) {
        if (Vector3.Distance(transform.position, player.position) < 50f) {
            // 玩家接近才執行昂貴決策
            RunExpensiveAILogic();
        }
        yield return new WaitForSeconds(5f); // 每 5 秒檢查一次
    }
}

協同程式 vs Update 對比

特性UpdateCoroutine
呼叫頻率每幀 (60+ Hz)自訂 (yield return null = 下一幀; WaitForSeconds = 秒級)
狀態保持需靠成員變數局部變數自動保持(狀態機)
可讀性分散在多幀線性寫法,邏輯集中
除錯難中斷點可在 yield 處中斷

禁止在 Update/FixedUpdate 使用 yield

Unity 不允許在 Update/FixedUpdate 直接 yield,必須另寫 IEnumerator 方法並用 StartCoroutine 啟動。

總結:優化決策樹

  1. 邏輯**完全不需要**時 → enabled = false / GameObject.SetActive(false)。
  2. 需**低頻檢查** → 協同程式 WaitForSeconds。
  3. 需**玩家接近觸發** → Trigger 碰撞體。
  4. 需**畫面可見才跑** → OnBecameVisible。
  5. 需**每幀跑但可分帧** → 協同程式 yield return null 分攤負載。
copyright © 萬盛學電腦網 all rights reserved