Unity Concepts: Update VS FixedUpdate Vs LateUpdatePosted by on


Update VS FixedUpdate Vs LateUpdate

At lot of new developers have a wish I knew then what I do now moments when it comes to understanding why and when to use these functions.  Throughout this article we will take a look at and discover what exactly is the difference between these Update() functions and when is the best approach to use each one.

When you first create a new script from within the Unity Editor, Unity will create a shell script that will contain some basic mono helper functions to get you started with like Start() and Update().  Chances are though,  most of us are already at home and familiar with that particular Update function.

However, did you know there are also other Update functions that as developers we can use to take our projects to the next level?

A quick google search reveals a lot of people putting hard working functions inside the Update function and having extremely strange results.    By calling the function in a LateUpdate() function could provide a visual performance impact.

Taking a look at the script that Unity creates we are provided with some simple information into what Update() is doing.  It’s called once per frame.  We use the Start() function for any logic that needs to be called before the initial Update() call.

When it comes to understanding the Update functions we come to learn that there are 3 Update functions that require our attention and each one has a best use case and approach.

As developer’s, we are constantly keeping track of various gameObject interactions, animations, transforms, cameras, etc… all the while trying to find the best way to effectively manage these behind the scenes without impacting the user experience.

Thankfully,  we actually have a few different ways we can approach and manage this challenges by utilizing the various update functions.

When it comes to design patterns of unity scripts, the most common pattern is to have the majority of the script logic tasks performed inside the Update() function.   Which for most cases due to the hardware these days that’s never going to be a problem.

There will be times however, when doing that will have a negative impact on your project and you need to squeeze out some of this lost performance.

Don’t worry, we are here to show you there are also other functions that you can approach and use to achieve the desired result.   The  Update() while can be a great place to perform the majority of logic, once your project becomes more and more complicated, things can go sideways, fast.


Lets take a look at the basic’s of each of the three Update functions that are available.

Update

Unity will call the Update() function once per frame.   That means, if your running at 60fps which translates to being called 60 times a second.  It’s due to this that the biggest issue when using the Update() function for absolutely everything is that it can vary out of step with the physics engine.   The calling behavior can change as it can wind up either going faster or slower, which depending on how much of a load your graphics are putting on the hardware doing the rendering, using Update for physics can cause the entirely wrong reaction.

This is the approach of utilizing a different Update function would be the right on, if you guessed FixedUpdate() then you would be correct as this one would result in the best overall improvement.

Fixed Update

Unity will indeed try to call FixedUpdate() at the project’s desired rate.  However, those calls also are also required to fit within discrete frames themselves.   What this means is that while there may be zero, one, or even more than 100 calls on any given frame, Unity will dynamically adjust to what the actual frame rate is.   By Digging deeper we come to realize this also means that all calls to FixedUpdate() are not necessarily on the specified interval.

FixedUpdate() can run once, zero, or several times per frame, depending on how many physics frames per second are set in the time settings, and how fast/slow the frame rate is.  So when this approach is not what we need, if you guessed LateUpdate(), then you would be correct.  The third time’s the charm as they day.

Late Update

Unity will call LateUpdate() after all Update functions have been called.   This is especially useful when discerning order execution of the script.   Let us consider why its common practice that a follow camera should always be implemented in LateUpdate().   The answer might be obvious as to why, but when we consider what LateUpdate() is for we realize we do this because the camera is tracking objects that may have already moved inside Update().

Now that we have discussed the differences of each of the Update() functions we will now look at the order of execution.  This will further demonstrate the differences between them.


Summarized Points of each Update Function

FixedUpdate

  • FixedUpdate() is often called more frequently than Update().
  • FixedUpdate()can be called multiple times per frame, however if the frame rate is low and it may not be called between frames at all.
  • FixedUpdate()may also not be called if the frame rate is high.
  • All physics calculations and updates occur immediately after FixedUpdate().
  • FixedUpdate() should be used when applying forces, torques, or other physics-related functions.
  • FixedUpdate() is called on a reliable timer, independent of the frame rate so when applying movement calculations inside FixedUpdate(), you do not need to multiply your values by Time.deltaTime.

TLDR; FixedUpdate()is commonly used for performing physics related task, like applying force on rigidbody since it will be executed exactly in sync with the physics engine itself.

Update

  • Update() is called once per frame, consider your project is running at 60 frames per second, this in turn translates to Update being called 60 times a second.
  • Update() is the main workhorse function for frame updates.
  • Update()is used for moving non physics objects.
  • Update()is used for receiving Input.
  • Update()is used for simple timer.

TLDR; Since this function can vary out of step with the physics engine, by either faster or slower, which also may depend on how much of a load the graphics are putting on the rendering engine at any given time can cause variable unknown results.  When used for physics, results could be dramatically different.

LateUpdate

  • LateUpdate() is called once per frame, after Update()has finished.
  • Any calculations that are performed in Update() will have completed when LateUpdate()begins.
  • A common use for LateUpdate() would be a following third-person camera.

TLDR; Since your character will move and turn inside Update(), we perform all camera movement and rotation calculations in LateUpdate() as this will ensure that the character has moved completely before the camera tracks its position.


Update Order

Now we will use a script to demonstrate the differences and the way each function is executed.   Simply copy this script into a new script in your project and attach it to a GameObject in your scene and press play.

Execution Order Time Script – Part #1

using UnityEngine;
using System.Collections;
public class DebuggingExecutionOrder : MonoBehaviour
{
    void FixedUpdate()
    {
        Debug.Log("FixedUpdate time :" + Time.deltaTime);
    }   
    
   void Update()
    {
        Debug.Log("Update time :" + Time.deltaTime);
    }
     
    void LateUpdate()
    {
       Debug.Log("late Update time :" + Time.deltaTime);
    }
}

Execution Order Time Results

Figure: B

Lets take a closer look at these results.  As you can see from Figure: A and Figure: B the actual timing differences between the various Update functions all start off being called in sync, at the same time as shown in Figure: A.   Everything looks fine and would appear to start off normal.   But as we let the program continue to run, things start to change.

As the program continues to run and things get going, we can start to see how fast they fall out of sync shortly after.  Keep in mind that this is also without any actual physics or game logic going on, we are just debugging out some information. Once those other variables like physics and cameras are introduced the timing will become even further apart.

This is why knowing when and which update approach to use can really impact the performance of your project.  Consider if you had a scene that had a bunch of AI’s walking around and interacting with the the environment which leads to putting a huge load on the physics engine that if you had everything running in the Update function.

You would find that your project would quickly approach the point where it becomes next to impossible to execute the required number of physics within each time step to keep everything appearing like it is running at a proper speed.

Anytime you have large numbers of complex objects such as those containing rigidbodys  and mesh colliders that are all clumped together you will have many collisions occurring every step.

If it doesn’t crash it will seem like you cant even move.   Let’s add a little more information to the script and take a closer look by adding in some  counters that we can see in the inspector since they are a [SerializedField] and of course through a debug log.


Execution Order Time Script – Part #2

Now we will alter the script to demonstrate the differences and times each function is executed.  As before, simply copy this script into a new script in your project and attach it to a GameObject in your scene and press play.

using UnityEngine; public class DebuggingExecutionOrder : MonoBehaviour
{
    [SerializeField] private int updateCalls = 0;
    [SerializeField] private int fixedUpdateCalls = 0;
    [SerializeField] private int lateUpdateCalls = 0;

    void FixedUpdate()
    {                  
       fixedUpdateCalls++;
        Debug.Log(string.Format("Times Fixed Update Called: {0} -- Current Update time : {1} ", fixedUpdateCalls, Time.deltaTime));
    }

    void Update()
    {
        updateCalls++;
        Debug.Log(string.Format("Times Update Called: {0} -- Current Update time : {1} ", updateCalls, Time.deltaTime));
    }

    void LateUpdate()
    {          
        lateUpdateCalls++;          
        Debug.Log(string.Format("Times Late Update Called: {0} -- Current Update time : {1} ", lateUpdateCalls, Time.deltaTime));
    } 
}

Figure: D

Figure: C

Now with the new information in the debug logs we can see the times it has been called and the current update time.

Everything again starts off find and in sync and quickly becomes something entirely different.

This is why using the best approach to achieve a specific result using the Update() functions will result in greater experience all around experience.

As mentioned earlier, most small projects may never be impacted by these kinds of things.

Breaking things up into scenes when working with a user interface rather then stacking panel upon panel.

 

 

 


Final Thoughts To Consider

Issue: Your project is running at a slow frame rate.
Step: Check for numerous physics updates between each visible frame render.

Issue: Your project is running at a very high frame rate.
Step: Check for missing physics steps between some of the frame renders.  Due to the elapsed time since the last rendered frame has not yet exceeded the time period of a single physics step.

Issue: Your project is left at the default physics timescale value (0.02).
Result: This means 50 physics updates per second and each physics step simulates the motion that occurs over the period of two-hundredths of a second.


We hope that any area’s that were fuzzy are now clear and those that have been trying to discern the differences between these functions have a better idea on how to use them.   Thank you for reading our article and hope you now have some clarity and extra things to consider when approaching the Update dilemma.

If your looking for more information or would like to watch an official video and learn more, click the following link =>  Official Link to Unity Learn

Image-Logo-AresTheDogStudio

ProgrammingUnity

C#Mono DevelopUnity

AresTheDogAuthor posts

AresTheDog Studio Administrator.

Leave a Reply

Your email address will not be published. Required fields are marked *