在網上看到一些資料說Unity3d的Update方法是如何如何很差,影響性能。做爲一個菜鳥,以前我還以爲挺好用的,徹底沒用什麼影響性能的問題存在。如今發現確實有很大的問題,我習慣把一大堆檢測判斷放在Update中去執行,這種檢測判斷每幀都在執行,而每每其中的方法可能只執行一次或幾回,這樣確實對性能有很大的影響。javascript
下面這種是我常用的寫法:java
[javascript] view plaincopyprint? function Update () { if (!wait) { transform.Translate(Vector3.forward * Time.deltaTime); } else if (Time.time >= timer) { wait = false; } if (Input.anyKeyDown) { wait = true; timer = Time.time + 1.0; } }
其實咱們徹底能夠這麼寫:性能
[javascript] view plaincopyprint? function Start () { while (true) { transform.Translate(Vector3.forward * Time.deltaTime); if (Input.anyKeyDown) { yield WaitForSeconds(1.0); } yield; } }
這樣簡單明瞭,並且不影響性能。下面是我摘自網上的一段代碼,使用coroutine替換update方法的例子:this
[csharp] view plaincopyprint? using UnityEngine; using System.Collections; /// /// Thinkgear user interface help message. /// /// By chiuan 2012.8.18 /// public class ThinkgearUIHelpMessage : MonoBehaviour { //the time gap that need to disable the component . const float _TimeToDisable = 0.2f; bool isNeedToDisable = false; #region for other call message or invoke. public void UnActiveObject() { isNeedToDisable = true; StartCoroutine("StartCheckDisable"); } public void ActiveObject() { if(isNeedToDisable == true) { //because this means the coroutine has started. //than u need to stop it,if u wanna active this . StopCoroutine("StartCheckDisable"); } isNeedToDisable = false; } #endregion IEnumerator StartCheckDisable() { yield return new WaitForSeconds(_TimeToDisable); if(isNeedToDisable) { gameObject.SetActiveRecursively(false); } } }