Update vs LateUpdate

In Unity, the Update and LateUpdate functions are commonly used to update the behavior of objects in a scene, and while they serve similar purposes, there are key differences between the two.

'Update'

The function 'Update' is called once per frame and is used for most general-purpose tasks, such as input handling and object movement. It's important to note that 'Update' is not frame-rate dependent, meaning it can vary in execution time depending on the performance.

void Update()
{
    // Input handling
    float horizontalInput = Input.GetAxis("Horizontal");
    float verticalInput = Input.GetAxis("Vertical");
    
    // Movement
    Vector3 movement = new Vector3(horizontalInput, 0, verticalInput);
    transform.Translate(movement * speed * Time.deltaTime);
    
    // General-purpose tasks
    // ...
}

In the example above, we retrieve input from the horizontal and vertical axes and use it to control the object's movement. The method 'Translate' is used to move the object in the specified direction at a constant speed. General-purpose tasks can also be performed within the function 'Update'.

'LateUpdate'

The 'LateUpdate' function is also called once per frame, but it is executed after all the functions 'Update' have been completed. It is commonly used to ensure that other updates, like object movement or animation, have finished before performing additional actions that depend on those updates.

void LateUpdate()
{
    // Camera follow
    Vector3 desiredPosition = target.position + offset;
    transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothness);
    
    // Additional actions after other updates
    // ...
}

In the example above, the function 'LateUpdate' is used to smoothly follow a target object with a camera. It ensures that the camera's position is updated after the target's movement has been processed in the 'Update' functions. Additional actions that depend on the object's updated position can also be performed within 'LateUpdate'.

'Update' vs 'LateUpdate'

Key differences between functions 'Update' and LateUpdate:

  • 'Update' is called first in the frame, followed by LateUpdate.
  • 'Update' is suitable for most general-purpose tasks, including input handling, object movement, and non-camera-related operations.
  • LateUpdate is commonly used for camera-related tasks, such as smoothly following a target object or performing actions dependent on other updates.
  • Using LateUpdate helps ensure that actions dependent on other updates occur after those updates have been processed.

Conclusion

It's worth noting that both 'Update' and 'LateUpdate' can coexist in the same script, allowing to separate different types of updates. Understanding the differences and utilizing the appropriate function in each context helps to achieve the desired behavior in the Unity projects.

Links
Unity 6