0
0
Unityframework~5 mins

MonoBehaviour lifecycle in Unity

Choose your learning style9 modes available
Introduction

The MonoBehaviour lifecycle helps you control when your game code runs. It organizes your code to run at the right time during the game.

When you want to run code once at the start of a game or scene.
When you need to update something every frame, like moving a character.
When you want to react to physics updates in your game.
When you want to clean up or save data before the game or scene ends.
When you want to respond to user input or other events during gameplay.
Syntax
Unity
void Awake() { }
void Start() { }
void Update() { }
void FixedUpdate() { }
void LateUpdate() { }
void OnEnable() { }
void OnDisable() { }
void OnDestroy() { }

These are special methods in a MonoBehaviour script that Unity calls automatically.

You do not call these methods yourself; Unity manages when they run.

Examples
Awake runs first when the script instance is loaded.
Unity
void Awake() {
    Debug.Log("Awake called");
}
Start runs once before the first frame update, after Awake.
Unity
void Start() {
    Debug.Log("Start called");
}
Update runs every frame to handle regular updates like input or movement.
Unity
void Update() {
    Debug.Log("Update called every frame");
}
FixedUpdate runs on a fixed timer, good for physics calculations.
Unity
void FixedUpdate() {
    Debug.Log("FixedUpdate called on fixed time steps");
}
Sample Program

This script shows the main MonoBehaviour lifecycle methods. Unity calls them automatically in this order: Awake, Start, then Update every frame, FixedUpdate on fixed intervals, and OnDestroy when the object is removed.

Unity
using UnityEngine;

public class LifecycleExample : MonoBehaviour
{
    void Awake()
    {
        Debug.Log("Awake: Initialize variables");
    }

    void Start()
    {
        Debug.Log("Start: Setup before first frame");
    }

    void Update()
    {
        Debug.Log("Update: Runs every frame");
    }

    void FixedUpdate()
    {
        Debug.Log("FixedUpdate: Runs on fixed time steps");
    }

    void OnDestroy()
    {
        Debug.Log("OnDestroy: Cleanup before object is destroyed");
    }
}
OutputSuccess
Important Notes

Awake is called even if the script is disabled, but Start only runs if the script is enabled.

Update runs every frame, so keep code here efficient to avoid slowing the game.

FixedUpdate is best for physics-related code because it runs at consistent time steps.

Summary

MonoBehaviour lifecycle methods let you run code at specific times during the game.

Awake and Start run once at the beginning; Update and FixedUpdate run repeatedly.

Use OnDestroy to clean up before the object is removed.