Welcome to the land of OOP – Object-Oriented Programming.
Don’t run. It sounds fancy, but it’s actually what you’ve already been doing this whole time.
In Unity, every script is a class. Every object in your scene is (you guessed it) an object.
Let’s break it down and make sense of it all.
🧠 What is a Class?
A class is a blueprint.
It describes what something is, and what it can do.
Example:
public class Enemy
{
public int health = 100;
public void TakeDamage(int amount)
{
health -= amount;
}
}
This is a blueprint for an Enemy.
It says: “I have health. I can take damage.”
But on its own, it doesn’t exist in the game yet.
👤 What is an Object?
An object is a real, living version of that blueprint.
In Unity, when you attach a script to a GameObject, Unity creates an instance (object) of that class.
You can also create multiple objects from the same class:
Enemy goblin = new Enemy();
Enemy troll = new Enemy();
goblin.TakeDamage(20);
troll.TakeDamage(50);
Now we have two enemies — each with their own health.
🧰 Unity + MonoBehaviour = Magic
In Unity, your scripts usually extend (inherit from) MonoBehaviour
:
public class Player : MonoBehaviour
{
public int health = 100;
void Start()
{
Debug.Log("Player spawned!");
}
}
MonoBehaviour gives you access to Unity-specific magic like:
Start()
,Update()
,OnCollisionEnter()
- Inspector visibility for public fields
- Component access via
GetComponent<>()
Basically, it plugs your code into the Unity engine.
🧪 Example: Player + Enemy System
Let’s say you want each enemy to have its own health and logic:
public class Enemy : MonoBehaviour
{
public string enemyName;
public int health;
public void TakeDamage(int amount)
{
health -= amount;
Debug.Log(enemyName + " took " + amount + " damage!");
}
}
Now you can:
- Add this script to any enemy GameObject
- Customize their health and name in the Inspector
- Call
TakeDamage()
from another script when needed
🎉 Boom — reusable, scalable logic!
🤓 Why Use Classes?
- ✅ Reuse logic across objects (DRY = Don’t Repeat Yourself)
- ✅ Keep code modular and organized
- ✅ Create cleaner, more maintainable games
- ✅ Add powerful structure to bigger projects
Even the Unity components like Rigidbody2D
, Camera
, and Transform
… are all classes!
🧪 Mini Challenge: Create an Enemy Army
- Create a script
Enemy.cs
with:public string enemyName
public int health
public void TakeHit(int damage)
that logs a message
- Create 3 GameObjects in the scene with different names and health
- Call
TakeHit()
from another script to damage each one
Optional: Make enemies explode into a dramatic Debug.Log.
🚀 What’s Next?
Now that you know how to write reusable scripts and build structured logic, it’s time to learn how Unity handles code in motion — with its unique built-in methods like Start()
and Update()
.
⚙️ Go to Lesson 12 → Unity-Specific Scripting (MonoBehaviour
, Start, Update)