Overview
When creating C# scripts in Unity, you'll always see public class MyScript : MonoBehaviour. What exactly is this MonoBehaviour?
MonoBehaviour is a crucial "base class" that connects Unity's API to your custom scripts. By inheriting from this class (writing it after the :), your script can be added as a component to GameObjects, receive lifecycle events like Update and Start, and access convenient properties like transform and gameObject.
This article explores the role of MonoBehaviour—the foundation of Unity programming—and the key features it provides.
MonoBehaviour's Role
The main benefits of inheriting from MonoBehaviour:
- Componentization: Your script can be attached as a component to GameObjects, adding behavior to objects.
- Lifecycle Event Reception: Use event functions that are automatically called at specific Unity-defined timings—
Awake,Start,Update, etc. - Access to Key Properties: Easily access the GameObject the script is attached to and its Transform component.
- Coroutine Execution: Use
StartCoroutineto execute time-consuming processes asynchronously.
If you create a plain C# class without inheriting MonoBehaviour (sometimes called POCO - Plain Old C# Object), it cannot be attached to GameObjects and won't receive lifecycle events. Such classes are used for data storage or calculations, called from MonoBehaviour scripts.
Key Properties and Methods
Within scripts inheriting MonoBehaviour, many convenient properties and methods are directly callable. Here are the most frequently used:
transform
Returns a reference to the Transform component of the GameObject this script is attached to. Frequently used for manipulating object position, rotation, and scale. This is a shortcut for GetComponent<Transform>()—provided specially because it's used so often.
using UnityEngine;
public class PositionChanger : MonoBehaviour
{
void Start()
{
// Use the transform property to set the object's Y position to 5
transform.position = new Vector3(0, 5, 0);
}
}
gameObject
Returns a reference to the GameObject itself that this script is attached to. The starting point for deactivating objects or getting other components.
using UnityEngine;
public class ObjectController : MonoBehaviour
{
void Start()
{
// Deactivate this GameObject after 5 seconds
Invoke("DeactivateObject", 5f);
}
void DeactivateObject()
{
// Use gameObject property to deactivate itself
gameObject.SetActive(false);
}
}
GetComponent<T>()
Gets a reference to a component of the specified type T attached to the same GameObject. The most fundamental method for communicating with other components in Unity's component-oriented design.
using UnityEngine;
public class PlayerHealth : MonoBehaviour
{
private Rigidbody rb;
void Start()
{
// Get the Rigidbody component on the same GameObject
rb = GetComponent<Rigidbody>();
if (rb != null)
{
// If Rigidbody found, set its mass to 10
rb.mass = 10f;
}
}
}
Performance tip: GetComponent<T>() is a relatively expensive operation. Avoid calling it in functions called every frame like Update()—call once in Awake() or Start() and cache the result in a variable.
Instantiate() and Destroy()
Instantiate(original): Creates a clone oforiginal(a Prefab or existing GameObject) in the scene. Used for dynamically spawning enemies, bullets, effects.Destroy(obj): Destroys the specified GameObject, component, or asset. Used for removing unnecessary objects from the scene.
using UnityEngine;
public class BulletSpawner : MonoBehaviour
{
public GameObject bulletPrefab;
void Update()
{
// When Space is pressed
if (Input.GetKeyDown(KeyCode.Space))
{
// Spawn a bullet from the Prefab
GameObject newBullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity);
// Destroy that bullet after 3 seconds
Destroy(newBullet, 3f);
}
}
}
Summary
MonoBehaviour is the class at the heart of Unity scripting. By inheriting from it, our C# code can finally interact with Unity's world and bring GameObjects to life.
MonoBehaviouris the bridge between Unity and your scripts.- Inheriting enables component behavior and lifecycle event reception.
- Provides convenient properties and methods like
transform,gameObject,GetComponent<T>().
Unity development largely depends on how well you master MonoBehaviour. Start by getting familiar with the basic properties and methods introduced here.