Skip to main content
C# for Games – Complete Beginner to Advanced Guide
CHAPTER 05 Beginner

Object-Oriented Programming for Games

Updated: May 16, 2026
30 min read

# CHAPTER 5

Object-Oriented Programming for Games

1. Introduction

Up to this point, we have written all our variables and methods inside one giant file. If you are building Pong, that is fine. If you are building *The Witcher*, that will end in disaster. How do you manage 50 different enemies, each with their own health, speed, and attack methods? You use Object-Oriented Programming (OOP). OOP is a design philosophy where you bundle data (variables) and behaviors (methods) together into distinct entities called Classes. In this chapter, we will master the core pillars of OOP. We will learn how to write a blueprint (Class), spawn entities from it (Objects), and share behaviors between them (Inheritance).

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define a Class to act as a blueprint for game entities.
  • Instantiate new Objects from a Class in memory.
  • Understand Encapsulation (Public vs. Private access modifiers).
  • Use Inheritance to create subclasses (e.g., Orc inherits from Enemy).
  • Understand Polymorphism (Overriding base behaviors).

3. Classes and Objects (The Blueprint and the House)

A Class is a blueprint. It does not exist in the game. It just defines what an entity *should* look like. An Object (or Instance) is the actual house built from that blueprint. It lives in the computer's memory.
csharp
12345678910111213141516
// The Blueprint (Class)
public class Player
{
    public string Name;
    public int Health = 100;

    public void TakeDamage(int amount)
    {
        Health -= amount;
    }
}

// Building the Object (Instantiating)
Player player1 = new Player(); // Creates a new Player in memory
player1.Name = "Arthur";       // Accessing its specific variables
player1.TakeDamage(20);        // Calling its specific method

4. Encapsulation (Protecting the Data)

You don't want the UI system to accidentally set the Player's health to -5000. You must protect your variables using Access Modifiers.
  • public: Any other script can see and change this variable.
  • private: Only the script it lives inside can see or change it. (This is the default).
By making Health private, and creating a public TakeDamage() method, you force other scripts to follow your rules.

5. Inheritance (Sharing the DNA)

Imagine making a Goblin, an Orc, and a Dragon. They all have Health, Speed, and a Die() method. Instead of writing that code three times, you create a Parent class called Enemy. Then, the specific monsters Inherit from it.
csharp
1234567891011121314
// Parent Class (Base)
public class Enemy
{
    public int Health = 50;
    public void Walk() { Console.WriteLine("Walking..."); }
}

// Child Class (Derived) uses the colon ':' to inherit
public class Dragon : Enemy 
{
    public void BreatheFire() { Console.WriteLine("FWOOSH!"); }
}

// The Dragon gets 'Walk()' and 'Health' automatically for free!

6. Polymorphism (Overriding Behavior)

What if the Parent Enemy class has an Attack() method, but the Dragon needs to attack differently than a Goblin?
  • You mark the parent method as virtual (meaning it *can* be changed).
  • You mark the child method as override (meaning "ignore the parent, do it my way").
csharp
1234567
public class Enemy {
    public virtual void Attack() { Console.WriteLine("Punch!"); }
}

public class Dragon : Enemy {
    public override void Attack() { Console.WriteLine("Fireball!"); }
}

7. Visual Learning: Inheritance Tree

txt
123456789
                  [ Class: Enemy ]
                  - int Health
                  - void TakeDamage()
                         |
           +-------------+-------------+
           |                           |
[ Class: Goblin ]             [ Class: Dragon ]
- void StealGold()            - void BreatheFire()
- override Attack()           - override Attack()

8. Best Practices

  • Composition over Inheritance: While Inheritance is powerful, don't create massive, 10-layer deep family trees (e.g., Entity -> Living -> Enemy -> Boss -> Dragon). It becomes impossible to maintain. Modern game engines (like Unity) heavily favor *Composition*—attaching small, reusable Component scripts (like a HealthComponent and a FireComponent) to an empty GameObject.

9. Common Mistakes

  • Null Reference Exceptions: A beginner writes Player myPlayer; and then immediately tries to write myPlayer.TakeDamage(10);. The game instantly crashes. Why? Because Player myPlayer; only creates an empty label. You MUST use the new keyword (myPlayer = new Player();) to actually build the object in the computer's RAM before you can use it!

10. Mini Project: Build an RPG Battle System

Objective: Create classes, instantiate objects, and use inheritance.
  1. 1. Open your Console App. Replace the code with:
csharp
123456789101112131415161718192021222324252627282930313233343536373839404142434445
using System;

// 1. The Base Class
public class Character
{
    public string Name;
    public int Health = 100;

    public virtual void Attack(Character target)
    {
        Console.WriteLine(Name + " attacks " + target.Name + " for 10 damage!");
        target.Health -= 10;
    }
}

// 2. The Child Class
public class Boss : Character
{
    public override void Attack(Character target)
    {
        Console.WriteLine(Name + " uses MEGA SMASH on " + target.Name + " for 40 damage!");
        target.Health -= 40;
    }
}

class Program
{
    static void Main()
    {
        // 3. Instantiate Objects
        Character hero = new Character();
        hero.Name = "Arthur";

        Boss evilKing = new Boss();
        evilKing.Name = "Sauron";
        evilKing.Health = 500;

        // 4. Battle!
        hero.Attack(evilKing);
        evilKing.Attack(hero);

        Console.WriteLine(hero.Name + " HP: " + hero.Health);
        Console.WriteLine(evilKing.Name + " HP: " + evilKing.Health);
    }
}

11. Practice Exercises

  1. 1. What keyword is used in C# to create a brand new instance of an object in memory?
  1. 2. Explain the difference between public and private access modifiers.

12. MCQs with Answers

Question 1

You are designing an Enemy class. You want to allow child classes (like Skeleton and Zombie) to completely change how the Attack() method works. Which keyword must you place in the Parent's Attack() method definition?

Question 2

Which OOP principle prevents a UI script from directly changing player.Health = 9999 by hiding the variable and forcing the UI to use a public method like player.Heal(50)?

13. Interview Questions

  • Q: Explain the four pillars of Object-Oriented Programming (Encapsulation, Inheritance, Polymorphism, Abstraction) and provide a concrete game development example for each.
  • Q: A junior developer receives a NullReferenceException when calling player.Attack(). Explain what this error means in the context of Classes and Objects, and how the new keyword prevents it.
  • Q: Contrast Inheritance with Composition. Why do modern engines like Unity prefer a Component-based architecture over deep Inheritance trees?

14. FAQs

Q: Do I always have to use OOP? A: Most game engines (Unity, Unreal, Godot) are inherently designed around OOP concepts. However, highly complex, performance-critical games (like City Skylines) are shifting toward a new architecture called DOTS (Data-Oriented Technology Stack) which abandons OOP for raw data processing. For 95% of games, OOP is the absolute standard.

15. Summary

In Chapter 5, we moved from writing scripts to engineering software. We embraced Object-Oriented Programming, learning how to bundle our chaotic variables and methods into neat, logical Classes. We instantiated living Objects into memory using the new keyword. We protected our game logic using Encapsulation (public/private), shared behaviors to save time using Inheritance, and overrode behaviors using Polymorphism. We are now thinking like software architects.

16. Next Chapter Recommendation

We can create one Enemy, but how do we manage an army of 50 enemies? How do we hold 20 items in a backpack? Proceed to Chapter 6: Arrays, Lists, and Collections.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·