Update 和 LateUpdate
本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 71 课,共 85 课。
每一帧,Unity 都会对每个脚本调用 Update(),只有等所有脚本都执行完后,才会对每个脚本调用 LateUpdate()。哪个对象的 Update() 先执行,不由你决定。
对于依赖其他事物的内容,这一点很重要。如果摄像机在 Update() 中复制玩家的位置,它可能会在玩家自己的 Update() 移动玩家之前运行,于是摄像机复制到的是玩家一帧前的位置:摄像机会落后一步,而且添加对象或重新加载场景时,这种情况是否发生可能会改变。在 LateUpdate() 中,复制总是在玩家移动后进行:
public Transform player;
public Vector3 offset = new Vector3(0, 3, -6);
void LateUpdate()
{
transform.position = player.position + offset;
}规则是:在 Update() 中移动物体,并将根据物体最终位置作出反应的代码放在 LateUpdate() 中,例如摄像机、标签和瞄准。两者每帧都会运行一次,而且 Time.deltaTime 在两者中的含义相同。
挑战
中等让名字标签在每一帧都正好位于玩家上方。
- 添加
void LateUpdate(),它会在每个脚本的Update()运行之后运行。 - 将
if (target != null)部分移到其中,并且只在Update()中保留箭头移动,将其放在if (target == null)下。
按下 运行 并按住一个方向键:标签会保持在玩家正上方。然后点击 检查。
亲手试试
using UnityEngine;
public class Mover : MonoBehaviour
{
public Transform target;
public Vector3 offset;
public float speed = 4f;
void Update()
{
if (target != null)
{
transform.position = target.position + offset;
}
else
{
if (Input.GetKey(KeyCode.RightArrow))
{
transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.position -= new Vector3(speed * Time.deltaTime, 0, 0);
}
}
}
}
Unity 脚本基础中的所有课
自己练习: Unity 在线编辑器