Update and LateUpdate
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 71 of 85.
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
MediumMake the name tag sit exactly above the player on every frame.
- Add
void LateUpdate(), which runs after every script'sUpdate(). - Move the
if (target != null)part into it, and keep only the arrow movement inUpdate(), underif (target == null).
Press Play and hold an arrow: the tag stays right above the player. 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);
}
}
}
}
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling Star12The Script Lifecycle
Awake and StartUpdate and LateUpdateOnEnable and OnDisableThe Lifecycle OrderRecap: Lifecycle LoggerPractice on your own: Unity playground