Loading lessons...
Scripting Basics & MonoBehaviour
Scripting Basics & MonoBehaviour
To create custom interactive logic, AI behaviors, or game rules in Unity, you write code in the C# programming language. Scripts act as custom components that you attach to GameObjects.
1. Creating and Compiling a Script
To create a new script:
- In the Project Window, right-click in your assets folder and select Create -> C# Script.
- CRITICAL: Type the name of the script immediately (e.g.,
PlayerController) and press Enter. The script file name and the C# class name declared inside the file must match exactly. If you rename the file later, you must manually open the script and rename the class inside to match, otherwise Unity will fail to attach the script to GameObjects. - Double-click the file to open it in your code editor (e.g., Visual Studio, VS Code, or Rider).
- Save the file. When you switch back to the Unity Editor, it detects the changes and automatically compiles the C# code. If there are syntax errors, they will appear in red in the Console Window, and you will be unable to run the game until they are fixed.
2. Attaching Scripts to GameObjects
Once a script compiles successfully, it functions as a component:
- To attach it, drag the script file from the Project Window and drop it onto any GameObject in the Hierarchy or the Inspector Window.
- Alternatively, select the GameObject, click Add Component in the Inspector, search for your script's name, and select it.
3. Understanding the MonoBehaviour Base Class
By default, every new C# script you create in Unity derives from MonoBehaviour:
using UnityEngine; // Provides access to Unity's core APIs
public class PlayerController : MonoBehaviour
{
// Script code goes here
}
Inheriting from MonoBehaviour grants your class special abilities:
- It can be attached to GameObjects as a component.
- It receives automatic callback event functions from the Unity engine (like
StartandUpdate). - It has built-in access to the GameObject it is attached to (via the
gameObjectproperty) and its Transform component (viatransform).
4. Serializing Variables (The Inspector)
To adjust script settings without editing code, you can expose variables to the Unity Inspector:
- Public Variables: Any public field is automatically serialized and visible in the Inspector.
- Private Variables with
[SerializeField]: To follow clean coding standards (encapsulation), keep variables private but add the[SerializeField]attribute above them to make them editable in the Inspector:
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// Visible and editable in the Inspector:
[SerializeField] private float moveSpeed = 5.5f;
// Hidden from the Inspector, only accessible inside this script:
private int playerLevel = 1;
}
5. Essential Event Methods: Start and Update
Unity generates two default callback methods in new scripts:
Start(): Invoked once when the script is enabled, right before the first frame update. Perfect for setting up initial states, initializing variables, or fetching component references.Update(): Invoked once every frame. Because it runs continuously, it is the primary place to check for player input, decrement timers, or execute real-time movement calculations.
TL;DR
- C# scripts act as custom components that attach to GameObjects.
- Class names must match script file names exactly to prevent attachment errors.
- Derive from
MonoBehaviourto access Unity events and properties. - Use the
[SerializeField]attribute to safely expose private fields in the Inspector. Startruns once at initialization;Updateruns on every frame render.