Menu
CoddyTech

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 icon

Challenge

Medium

Make the name tag sit exactly above the player on every frame.

  1. Add void LateUpdate(), which runs after every script's Update().
  2. Move the if (target != null) part into it, and keep only the arrow movement in Update(), under if (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

Practice on your own: Unity playground