🏠 Home

MonoBehaviour in Unity

In Unity, most game objects are controlled using C# scripts. Almost every script you create manually inherits from the base class MonoBehaviour. This class enables Unity to manage object behavior: calling your code at game start, every frame, during collisions, and in other situations.

To create such a script:

  1. In the Assets window, right-click
  2. Select Create β†’ MonoBehaviour Script
  3. Give it a name, e.g., CSharpScript
  4. Double-click it to open in the editor

You'll see a code template like this:


using UnityEngine;

public class CSharpScript : MonoBehaviour
{
    // Start is called once when the object starts
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
  

using UnityEngine; β€” includes core Unity functionality.
public class CSharpScript : MonoBehaviour β€” creates a class with a name that must match the filename. Unity requires this for the script to work properly.

When the game starts, Unity calls Start() once, then automatically runs Update() every frame β€” this forms the core game loop.

In addition to these, Unity provides many other methods that get called at specific times β€” when the object is created, collides with something, gets enabled or disabled, etc. Below is a list of the most commonly used events that define a script’s lifecycle.

🧱 Object Lifecycle Events

Method When It's Called
Awake() πŸ“¦ Before Start(), when the script or object is created
Start() πŸš€ Called once before the first Update()
Update() πŸ•’ Called every frame (ideal for input and animation)
FixedUpdate() βš™οΈ Called at fixed intervals (ideal for physics)
OnEnable() βœ… When the object or script becomes active
OnDisable() ❌ When the object or script gets disabled
OnDestroy() πŸ’₯ When the object is destroyed or the scene closes

🧲 Physics (Collision and Trigger)

Method When It's Called
OnCollisionEnter() ⚑ When the object collides with another (with Collider and Rigidbody)
OnCollisionStay() β™» While the objects remain in contact
OnCollisionExit() πŸƒ When the contact ends
OnTriggerEnter() πŸšͺ When entering a trigger collider
OnTriggerStay() πŸ” While inside the trigger
OnTriggerExit() 🚢 When exiting the trigger

πŸ–±οΈ Mouse Interaction

Method When It's Called
OnMouseDown() πŸ–±οΈ When the object is clicked with the mouse
OnMouseUp() ☝ When the mouse button is released over the object
OnMouseEnter() πŸ‘€ When the cursor enters the object's area
OnMouseOver() πŸ” While the cursor is hovering over the object
OnMouseExit() πŸ™ˆ When the cursor leaves the object's area

πŸ“· Camera and Inspector

Method When It's Called
OnBecameVisible() πŸ“Έ When the object becomes visible to the camera
OnBecameInvisible() πŸŒ‘ When the object is no longer visible