更新、固定更新、延迟更新
Unity API 的一个突出部分是更新函数,这些函数是连续运行的函数。
Unity 具有三种类型的更新函数:'Update'、FixedUpdate 和 LateUpdate。
'Update' 与 FixedUpdate
'Update' 和 FixedUpdate 函数之间的区别在于它们运行的频率。
'Update' 函数每帧运行一次,而 FixedUpdate 以恒定速率运行,由 'Project Settings' -> 'Time' 中的 "Fixed Timestamp" 值控制。
'Update' 函数适合对游戏逻辑、玩家输入和基本上任何非物理计算进行编程。
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//Space button has been pressed
}
}
另一方面,FixedUpdate 函数适用于基于物理的计算,例如光线投射、向刚体施加力或任何需要与帧速率无关的计算。
void FixedUpdate()
{
//Use Physics Raycast to detect if there any object in front
RaycastHit hit;
if(Physics.Raycast(transform.position, transform.forward, out hit, 10))
{
Debug.Log("Object '" + hit.transform.name + "' is currently in front of this object.");
}
}
更新与 LateUpdate
'Update' 和 LateUpdate 在运行频率方面相同(均每帧运行一次),但 LateUpdate 在所有 'Update' 函数之后运行。
最后,LateUpdate 函数通常用于修改动画模型骨骼(例如,使玩家模型向上和向下看)或实现平滑的相机跟随。
void LateUpdate()
{
//Make camera tagged 'MainCamera' look at this object transform
Camera mainCamera = Camera.main;
mainCamera.transform.LookAt(transform);
}
带走
每个更新函数都有自己的用例。
结合使用它们来实现各种场景。