Unity3d中Update()方法的替身

      在网上看到一些资料说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); 
 } 
 } 
} 
相关文章
相关标签/搜索