Walk Through Monobehaviour

· 1 min read
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: