Menu
CoddyTech

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 icon

Challenge

Medium

The 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);
            }
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics