What is MonoBehaviour?

What is MonoBehaviour?

In Unity, C# is the main programming language. In our games, we can use every property of C#. However, if you have prior experience with C#, you are probably aware that the structure of a Unity script is different from what you see in C# books. This is because, in Unity, we use scripts that are inherited from the MonoBehaviour class. In this article, we will learn what exactly is MonoBehaviour.

MonoBehaviour is the base class that every Unity script has to be inherited. A Unity script, that is derived from a MonoBehaviour, serves a bunch of predefined functions(Awake, Start, Update, OnTriggerEnter, etc.) that are executed when an event occurs. This is a design preference that makes game development easier and faster.

Developing a complex game without a game engine is very hard and requires expertise in a lot of fields. Most of the code, which is the same for games, is already developed by Unity engineers including MonoBehaviour class.

Contents

Things to consider when writing Unity scripts

As we mentioned above every Unity script has to be derived from MonoBehaviour class. You cannot add a script to your game objects if it is not derived from MonoBehaviour. If you create your script in the Unity editor, the created script will be ready and derived. Therefore you do not need to worry about that.

Another thing to mention is that you should not use a constructor in a Unity script. It is not prohibited but you may see some behavior that you do not expect. Instead, you should use predefined methods like Awake(), Start() or OnEnable() in order to initialize your scripts.

MonoBehaviour Methods

Methods that come from MonoBehaivour are executed by UnityEngine. MonoBehaviour gives us lots of predefined methods to use for different situations. You can see the complete list of these methods in Unity documentation. Here I will talk about the most used ones.

Awake( )

Awake( ) method is used to initialize the script. You can put initial variables inside the Awake( ), or execute needed tasks at the beginning.

This method is called only once during the lifetime of the component whenever execution possible. For instance, if the game object that the script assigned is active at the beginning of the scene, it is executed at the beginning of the scene. If the game object instantiated at the runtime, it is executed when the object is created.

void Awake()
{
    Debug.Log("Awake method is always called before application starts.");
    Debug.Log("You can use it to initialize variables or execute tasks that are needed before the application starts.");
}

Start( )

Start( ) method is also used to initialize the script as Awake( ) method. However, Start( ) is executed after Awake( ) and before the first call of Update( ). Start( ) is also executed once in its lifetime.

For instance, add the following script to any active game object in your scene, and observe the console.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    void Awake()
    {
        Debug.Log("Awake method is always called before application starts.");
    }

    void Start()
    {
        Debug.Log("Start method is always called after Awake().");
    }
}

The result of the script above is the following:

Awake vs Start
Awake vs Start

Update( )

Update( ) is called in every frame. This means that if the frame rate of the game is 60 fps, then Update is called 60 times in a second. Since the frame rate of the application may differ from one device to another device, in Update method, you should avoid calling methods that need to consistent by time. For example, physics-related behaviors should not be written in the Update.

Update( ) method is called after Start( ) method. Observe the behavior of the following script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    void Awake()
    {
        Debug.Log("Awake method is always called before application starts.");
    }

    void Start()
    {
        Debug.Log("Start method is always called after Awake().");
    }

    void Update()
    {
        Debug.Log("Update method is called in every frame.");
    }
}

This will be the result if you execute the script above.

Awake, Start and Update
Awake, Start and Update

FixedUpdate( )

FixedUpdate( ) runs every fixed time intervals. Therefore, we write the behavior, that we want to execute frame rate independent behavior like physics, into FixedUpdate( ) method.

The time interval between two consecutive FixedUpdate calls is predefined and set to 0.02 seconds. You can change the fixed time intervals from the Time section under the Project Settings.

Changing fixed timesteps
Changing fixed timesteps

LateUpdate( )

LateUpdate( ) runs in every frame like Update( ). But it is executed shortly after the Update method is executed. It is generally used for calculations, that need to be done after everything has finished in a frame.

OnEnable( ) and OnDisable( )

OnEnable( ) and OnDisable( ) methods run whenever the script is enabled or disabled, respectively.

OnTriggerEnter( ), OnTriggerStay( ), and OnTriggerExit( )

These methods are only used with a game object that a collider attached. And the collider must be set as a trigger. They are called when a collider interacts with the game object. You can check this article for more information about Trigger and Collision Methods.

OnCollisionEnter( ), OnCollisionStay( ), and OnCollisionExit( )

These methods are similar to Trigger methods but this time collider must not be trigger. They are called when a collider collides with another collider.

The lifecycle of A MonoBehaviour Script

Above we talked about the most used built-in event functions that are in scripts inherit from MonoBehaviour class. Sure, these are only a small portion of the complete list.

It is useful to know the order of execution of these functions. Thus, you may avoid errors that are related to the execution order. For instance, it is not uncommon to try to reach a reference that is still null for those who do not aware of the order of execution.

You do not have to memorize the following flowchart but beware that every built-in event function is not executed randomly instead of in order. You may use the chart as a reference.

İsmail Çamönü

Hello, my name is İsmail. I am an indie game developer. I have been developing digital games for five years. I have released several games. I have BS degrees in electrical engineering and physics. I love arts and science. The idea of creating worlds and experiences brought me to the game development which is also directly related to the arts and science.

You may also like...

Leave a Reply

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