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:
CSharpScript
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.
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 |
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 |
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 |
Method | When It's Called |
---|---|
OnBecameVisible() |
πΈ When the object becomes visible to the camera |
OnBecameInvisible() |
π When the object is no longer visible |