🧱 Classes and Objects – Building Blocks of Game Logic

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:

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:

Now we have two enemies — each with their own health.


🧰 Unity + MonoBehaviour = Magic

In Unity, your scripts usually extend (inherit from) MonoBehaviour:

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:

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

  1. Create a script Enemy.cs with:
    • public string enemyName
    • public int health
    • public void TakeHit(int damage) that logs a message
  2. Create 3 GameObjects in the scene with different names and health
  3. 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)