Update and LateUpdate
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 56 of 67.
On every frame Unity calls Update() on every script, and only when all of them are done does it call LateUpdate() on every script. Which object's Update() goes first is not up to you.
That matters for anything that follows something else. A camera that copies the player's position in Update() may run before the player's own Update() has moved it, and then it copies where the player was a frame ago: the camera trails a step behind, and whether it does can change when objects are added or the scene is reloaded. In LateUpdate() the copy always happens after the player has moved:
public Transform player;
public Vector3 offset = new Vector3(0, 3, -6);
void LateUpdate()
{
transform.position = player.position + offset;
}The rule: move things in Update(), and put code that reacts to where things ended up, such as cameras, labels and aiming, in LateUpdate(). Both run once a frame, and Time.deltaTime means the same in both.
Challenge
MediumThe player and its name tag both run the Mover script. On the Player, target is empty, so the arrows move it. On the NameTag, target is the player, so the tag sits offset above it.
Press Play and hold an arrow: the tag trails behind the player. Here the tag's Update() runs first and copies where the player was a frame ago. Fix it so that the tag is exactly above the player on every frame, and keep the arrow movement in Update(). Then Check.
Try it yourself
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);
}
}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star10The Script Lifecycle
Awake and StartUpdate and LateUpdateOnEnable and OnDisableThe Lifecycle OrderRecap: Lifecycle Logger5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon