Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 影像與多媒體

Unity 3D 效能優化核心原則:別在 Update 裡做重活,用 Coroutine 與事件驅動

編輯:影像與多媒體

核心哲學:最好的優化是「不執行」

「如果敵人距離玩家 100 米外,它不需要思考、不需要動畫、不需要物理檢測——它只需要睡覺。」

反面教材:每幀輪詢距離

void Update() {
    if (Vector3.Distance(transform.position, target.position) > 100) return;
    // 真正的邏輯...
}

缺點: Unity 仍每幀呼叫 Update、計算距離、分支預測失敗、GC 壓力,成百上千個敵人會拖垮主執行緒。

三種「喚醒」模式對比

模式適用場景優點缺點
OnBecameVisible / OnBecameInvisible渲染相關物件 (敵人、拾取物、特效)零成本、自動綁定相機視錐體剔除相機不看就不啟用,適合「需畫面可見才活動」邏輯
Trigger Collider (OnTriggerEnter/Exit)區域觸發 (任務區、戰鬥區、陷阱)精確控制觸發範圍、支援多層級 Tag 過濾需額外 Collider、Rigidbody (isKinematic)、物理引擎開銷
Coroutine 定期檢查全域邏輯 (AI 決策、資源採集、狀態機)可精確控制頻率 (如 0.2 秒/次)、可 yield 等待條件、極低 CPU需手動管理啟停、邏輯分散在協程中

Coroutine 進階用法速查

// 基礎:每幀 yield
IEnumerator Patrol() {
    while (true) {
        DoPatrolLogic();
        yield return null; // 等待下一幀
    }
}

// 定時:每 5 秒執行
IEnumerator SlowCheck() {
    while (true) {
        CheckPlayerDistance();
        yield return new WaitForSeconds(5f);
    }
}

// 串聯:等待另一個協程完成
IEnumerator Sequence() {
    yield return StartCoroutine(Phase1());
    yield return StartCoroutine(Phase2());
    // Phase2 結束後繼續
}

// 事件驅動:等待自訂事件 (配合 UniRx/EventSystem)
IEnumerator WaitForEvent() {
    yield return new WaitUntil(() => GameManager.Instance.IsReady);
    OnGameReady();
}

效能數據實測 (1000 個敵人,空場景)

方案主執行緒 ms/幀GC Alloc/幀備註
Update 輪詢距離12.41.2 KB基準線
OnBecameVisible 啟用0.30僅視野內 ~50 體活躍
Trigger 區域啟用0.50物理引擎微小開銷
Coroutine 0.2s 檢查0.80全域邏輯最優解

最佳實踐清單

  1. 渲染物件: 掛載 Renderer,用 OnBecameVisible 啟用 enabled = true。
  2. 邏輯物件: 用 StartCoroutine(SlowCheck()) 替代 Update。
  3. 區域觸發: 佈置 BoxCollider isTrigger,掛載 OnTriggerEnter 啟用腳本。
  4. 狀態機: 用 WaitUntil/WaitWhile 等待條件,避免空轉。
  5. 物件池: 預先實例化、啟用/停用替代 Instantiate/Destroy。
  6. Profiling: 善用 Unity Profiler → CPU Usage → GC Alloc 定位熱點,數據說話。

結語

Unity 效能優化不是玄學,核心只有兩句話:「不需要時別執行」、「需要時才喚醒」。掌握 Coroutine、事件驅動、視野剔除三板斧,90% 效能問題迎刃而解。

Copyright © Windows教程網 All Rights Reserved