很多 Update()
内的代码实际上并不需要每帧调用(自行判断),可以考虑改用 FixedUpdate()
、Coroutine
InvokeRepeating()
或 限制代码的调用频率
详见下方代码示例
using System.Collections; | |
using UnityEngine; | |
public class TestComponent : MonoBehaviour | |
{ | |
private void Start() | |
{ | |
StartCoroutine(MyUpdateCoroutine()); //调用下面的异步方法 MyUpdateCoroutine | |
} | |
IEnumerator MyUpdateCoroutine() | |
{ | |
//通过异步循环来代替 Update() | |
while (true) //可以通过这个表达式来控制是否跳出循环 | |
{ | |
MyFunction();//你要调用的代码 | |
yield return new WaitForSeconds(0.5f); //等待0.5秒后继续执行这个循环 | |
//也可以直接用yield break;来跳出这个循环 | |
} | |
} | |
void MyFunction() | |
{ | |
//Codes... | |
} | |
} |
using UnityEngine; | |
public class TestComponent : MonoBehaviour | |
{ | |
void FixedUpdate()//固定频率、不受帧率影响 | |
{ | |
//代码片段 | |
} | |
} |
using UnityEngine; | |
public class TestComponent : MonoBehaviour | |
{ | |
private const float UpdateFrequency = 0.5f; | |
private float _timer = 0; | |
void Start() | |
{ | |
//第一帧的1秒后开始调用MyFunction,随后每0.5秒调用一次 | |
InvokeRepeating(nameof(MyFunction), 1, 0.5f); | |
} | |
void MyFunction() | |
{ | |
//Codes... | |
} | |
} |
using UnityEngine; | |
public class TestComponent : MonoBehaviour | |
{ | |
private const float UpdateFrequency = 0.5f; | |
private float _timer = 0; | |
void Update() | |
{ | |
//通过计时器来限制Update代码的执行频率 | |
if (_timer > UpdateFrequency) | |
{ | |
MyFunction(); | |
_timer = 0; | |
} | |
_timer += Time.unscaledDeltaTime; | |
} | |
void MyFunction() | |
{ | |
//Codes... | |
} | |
} |