在网上看到一些资料说Unity3d的Update方法是如何如何不好,影响性能。作为一个菜鸟,之前我还觉得挺好用的,完全没用什么影响性能的问题存在。现在发现确实有很大的问题,我习惯把一大堆检测判断放在Update中去执行,这种检测判断每帧都在执行,而往往其中的方法可能只执行一次或几次,这样确实对性能有很大的影响。
下面这种是我经常使用的写法:
[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方法的例子:
[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);
}
}
}