Update vs FixedUpdate vs LateUpdate
A prominent part of the Unity API is the update functions, which are the functions that run continuously.
Unity has three types of update functions: Update, FixedUpdate, and LateUpdate.
Update vs FixedUpdate
The difference between Update and FixedUpdate functions is in how often they run.
Update function runs once per frame while FixedUpdate runs at a constant rate, controlled by the "Fixed Timestamp" value in Project Settings -> Time.
Update functions are suitable for programming the game logic, player input, and basically any non-physics calculations.
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//Space button has been pressed
}
}
FixedUpdate functions are suitable for physics-based calculations, such as Raycasting, applying forces to Rigidbodies, or any calculations that need to be framerate independent.
void FixedUpdate()
{
//Use Physics Raycast to detect if there any object in front
RaycastHit hit;
if(Physics.Raycast(transform.position, transform.forward, out hit, 10))
{
Debug.Log("Object '" + hit.transform.name + "' is currently in front of this object.");
}
}
Update vs LateUpdate
Update and LateUpdate are identical in terms of run frequency (both run once per frame), but LateUpdate runs after all Update functions.
LateUpdate function is commonly used to modify animated model bones (ex. making the player model look up and down) or to implement a smooth camera follow.
void LateUpdate()
{
//Make camera tagged 'MainCamera' look at this object transform
Camera mainCamera = Camera.main;
mainCamera.transform.LookAt(transform);
}
Takeaway
Each update function has its own use case.
Use them in combination to implement a wide variety of scenarios.