You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Walk Through Monobehaviour


Like other fundamental parts such as GameObject, Compoent, Time, Input and Physics, Monobehaviour is an essential member for writing the script, which is the soul of an GameObject. This article is the introduction of the Monobehaviour.

MonoBehaviour Lifecycle

MonoBehaviour is the base class of all scripts in Unity. If you use JavaScript, the script will automatically inherit MonoBehaviour. If you use C#, you need to explicitly inherit MonoBehaviour.

When we use MonoBehaviour, we need to pay attention to the following methods:

Awake: Awake is called only once when a script instance is loaded. We mostly complete the initialization of member variables in this class.

Start: Similar to Awake, it is called only before the Update function. As it is called after Awake, we can initialize some variables that depend on Awake in Start. At the same time, we mostly execute StartCoroutine in this class to trigger some coroutines. Note that when writing scripts in C#, you must use StartCoroutine to start a coroutine, but if you are using JavaScript, you don't need to do this.

Update: When MonoBehaviour is enabled, its Update is called every frame. The number of runs depends on the hardware performance. Usually better hardware will run more with Update functions.

FixedUpdate: When MonoBehaviour is enabled, its FixedUpdate is called every fixed frame.

OnEnable: This function is called when the object becomes available or activated. For example, it will be called when gamobject.SetActive(true);

OnDisable: This function is called when the object becomes unavailable or inactive. Similar to OnEnable.

OnDestroy: This function is called when MonoBehaviour will be destroyed.

Here is an image on the life cycle methods: