In this article we are going to analyze Unity’s FixedUpdate method which allows us to make changes over time in our projects.
A method is a function defined in a script that can be executed and performs the task we define inside it. To learn more about methods in programming you can read this article or watch a video that summarizes the information.
Before continuing I leave a video in which I did some tests in Unity to better understand the methods Start, Update and FixedUpdate and how is the order of execution of them. To understand this will help you to detect the moments in the execution of the code in which it is convenient to carry out this or that task.
FixedUpdate Method in Unity – MonoBehaviours
The Update function is defined in the MonoBehaviour class and will run automatically in each frame of the game if the MonoBehaviour is active.
By default, the time between consecutive FixedUpdate runs is 20 milliseconds or 0.02 seconds. This time can be seen and modified in the tab Edit > Project Settings > Time – Fixed Timestep.
When we create a new Script in Unity, by default we’ll get some code already written. In this code is defined a Programming Class that is called equal to the name that we gave to the Script and that extends or inherits its behavior of MonoBehaviour, this in simple terms means that our Script is in itself a MonoBehaviour or a particular case of MonoBehaviour.
MonoBehaviours can be added to the GameObjects that are in the hierarchy, this can be done from the inspector using the “Add Component” button or simply dragging the Script to the GameObject inspector.
Execution of the FixedUpdate Function
While the game is running, Unity automatically takes all the MonoBehaviours on the scene and performs the FixedUpdate methods every time the “Fixed Timestep” time is met. So we don’t have to execute this method manually, the engine takes care of it.
This means that the FixedUpdate function will run periodically while our game is running.
Regardless of the FPS (frames per second) of our game, the FixedUpdate method will run at regular intervals, 50 times per second if the Fixed Timestep is set to 0.02 seconds.
Conclusion – FixedUpdate for evenly spaced changes in time
The FixedUpdate method represents the dynamic part of a game in Unity, when we want to produce changes in time and that these changes are applied at regular intervals, we resort to the FixedUpdate function.
A typical application of this function is to make the movement of objects or some animations that we do in a procedural way.
When moving objects in FixedUpdate, the speed of the object will be the one we indicate. If we move objects in the Update function, when our game runs at more FPS, the object will move faster than when the game runs slower.
It is useful to understand the order of execution of the Start, Update and FixedUpdate methods since it allows us to identify different moments in the execution of the game.