You’ve learned how to write scripts.
Now let’s learn how Unity knows when and how to run your code.
In Unity, there are special built-in methods — like Start()
, Update()
, and OnCollisionEnter()
— that Unity calls automatically at specific times.
This is made possible through MonoBehaviour
, Unity’s magical base class that connects your scripts to the engine.
👑 What is MonoBehaviour?
All your Unity scripts inherit from this class:
public class MyScript : MonoBehaviour
{
// Magic lives here
}
By inheriting from MonoBehaviour, Unity can call special methods like Start()
and Update()
without you needing to do anything else.
🧙 Think of MonoBehaviour as the wizard behind the curtain that hooks your code into the game loop.
🚀 Start()
– Runs Once
void Start()
{
Debug.Log("The game has started!");
}
- Called once at the very beginning (when the object becomes active)
- Great for initialization, setting values, or printing welcome messages
- Happens before the first
Update()
🔁 Update()
– Runs Every Frame
void Update()
{
Debug.Log("Still running...");
}
- Called every frame — 60+ times per second depending on your hardware
- Ideal for real-time logic like:
- Player input
- Moving objects
- Checking timers
💡 Too much heavy stuff in
Update()
= lag town. Use wisely.
🧪 Example Script
using UnityEngine;
public class HelloUnity : MonoBehaviour
{
void Start()
{
Debug.Log("Game started");
}
void Update()
{
Debug.Log("Frame running...");
}
}
Attach this script to a GameObject, hit play, and check the Console:
You’ll see “Game started” once, and “Frame running…” repeatedly.
🛠️ Other Useful MonoBehaviour Methods
Method | When it Runs |
---|---|
Awake() | Before Start() (used for internal setup) |
FixedUpdate() | Called at fixed intervals (physics-related) |
OnCollisionEnter() | When object collides with another |
OnTriggerEnter() | When trigger collider is entered |
OnDestroy() | When the object is removed from the scene |
We’ll explore these more in future lessons. For now, Start()
and Update()
are your go-to tools.
🧠 Recap
MonoBehaviour
connects your code to Unity’s event systemStart()
runs once when the object activatesUpdate()
runs every frame (use it for live logic)- These methods let your scripts become interactive parts of the game world
🧪 Mini Challenge: Frame Counter
- Create a new script called
FrameTracker.cs
- In
Update()
, increase a counter every frame - Every 60 frames, print
"One second-ish passed"
- Reset the counter after logging
Bonus: Try printing a message every 5 seconds using a float
timer instead!
🚀 What’s Next?
Congrats, you’ve finished Section 2! 🎉
You now know the basics of variables, methods, logic, loops, and Unity’s script lifecycle.
Next up, we’ll build our very first game together — a classic clicker game to put your skills into action!
👆 Go to Section 3 → Your First Game – Clicker Game