1. The Source of All Things — The MonoBehaviour Class
MonoBehaviour is the base class for all scripts in Unity. It provides a range of functionalities for implementing behaviors in game objects. By inheriting from MonoBehaviour, users can create custom scripts to control the lifecycle of game objects, respond to events, and manage game logic. It has the following key features:
Lifecycle Management: MonoBehaviour provides a series of event functions (such as `Awake()`, `Start()`, `Update()`, etc.) that help developers manage the lifecycle of objects.
Component System: Unity uses a modular design, and MonoBehaviour allows you to modularize functionality, making it easier to reuse code across different game objects.
Access to Unity API: Through MonoBehaviour, you can directly access many Unity features, such as the physics engine, rendering system, and input management.
Coroutine Support: MonoBehaviour supports coroutines, allowing you to execute code over a period without blocking the main thread.
2. What is the Script Lifecycle?
The script lifecycle refers to the execution order and timing of MonoBehaviour scripts in Unity. Understanding the script lifecycle is essential for writing effective game logic. Below are the main lifecycle event functions of MonoBehaviour and their order. For specifics on other event functions, you can refer to the Unity documentation:
1. Awake()
– **Timing**: Called when the script instance is loaded.
– **Purpose**: Used for variable or state initialization, typically executed before the game object is enabled.
2. OnEnable()
– **Timing**: Called when the object is enabled.
– **Purpose**: Suitable for subscribing to events or performing initialization tasks.
3. Start()
– **Timing**: Called before the first update.
– **Purpose**: Used for one-time initialization, ensuring all references are set.
4. Update()
– **Timing**: Called once per frame.
– **Purpose**: Handles per-frame logic updates, such as input handling and object movement.
5. FixedUpdate()
– **Timing**: Called at fixed time intervals.
– **Purpose**: Suitable for physics calculations (e.g., Rigidbody movement), as it executes at a fixed frequency.
6. LateUpdate()
– **Timing**: Called after all Update calls.
– **Purpose**: Used for operations that need to execute after all other updates, such as camera follow.
7. OnDisable()
– **Timing**: Called when the object is disabled.
– **Purpose**: Typically used to unsubscribe from events or clean up resources.
8. OnDestroy()
– **Timing**: Called before the object is destroyed.
– **Purpose**: Used for resource release or cleanup tasks.
3. What are Event Functions?
Event functions are a set of special methods provided by the MonoBehaviour class in Unity to respond to specific events or conditions. These functions are automatically called in particular contexts, allowing developers to implement dynamic behaviors for game objects. Here are some common event functions and their purposes:
– Awake(): Called when the script instance is loaded. Commonly used for variable initialization.
– OnEnable(): Called when the game object is enabled. Suitable for event subscription or initialization.
– Start(): Called before the first update. Used for one-time initialization.
– Update(): Called once per frame. Handles per-frame logic updates, such as input and movement.
– FixedUpdate(): Called at fixed time intervals. Suitable for physics calculations, like Rigidbody movement.
– LateUpdate(): Called after all Update calls. Used for operations that need to follow other updates, like camera follow.
– OnDisable(): Called when the object is disabled. Used for unsubscribing from events or cleaning up resources.
– OnDestroy(): Called before the object is destroyed. Used for releasing resources or performing cleanup tasks.
Physics and Collision Events:
– OnCollisionEnter(): Called when a collision occurs.
– OnCollisionExit(): Called when a collision ends.
– OnTriggerEnter(): Called when an object enters a trigger.
– OnTriggerExit(): Called when an object exits a trigger.
User Input Events:
– OnMouseDown(): Called when the mouse clicks on the game object.
– OnMouseUp(): Called when the mouse button is released.
4. Code Example
In the previous blog, we introduced Coroutines. In this example, we will understand the execution flow of key event functions in Unity through code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExecutionSequence : MonoBehaviour
{
int counter;// start is called before the first frame updatevoid start()
// Start is called before the first frame update
void Start()
{
StartCoroutine("myCoroutine");
print("start ends.");
}
// Update is called once per frame
void Update()
{
if (counter < 10) print("frame:" + counter++);
}
IEnumerator myCoroutine()
{
print("step1");
yield return null;
print("step2");
print("step3");
}
}
The execution order is as follows:
1. First, the `Start` method is called, which starts the coroutine `myCoroutine`, and the console outputs “step1”.
2. The coroutine reaches `yield return null;`, effectively pausing execution until the next frame (after the next `Update` call). The console then outputs “start ends.”.
3. The `Update` method is called for the first time, and the `counter` starts counting from 0, outputting “frame: 0” to the console.
4. When the `Update` method runs in the next frame (second call), it outputs “frame: 1”.
5. The coroutine resumes execution, printing “step2” and “step3” to the console. At this point, all content of the coroutine has been executed.
6. The `Update` method continues to be called until the `counter` reaches 9.
