computer4kids is now ComputerLeap. Same free lessons, same team. Read why we changed our name

← All lessons · 🧑‍💻 Coding Academy

🏗️

🎓

⏱ 30 min

Free

Classes, Objects & Properties

Model game characters with classes, constructors, properties and methods.

🎯 What you will learn

  • Create classes with constructors
  • Use auto-properties { get; set; }
  • Protect data with private setters

👋 Let’s get started!

In Unity, every player, enemy and coin is an object 🏗️. C# properties make it easy to expose data safely — a C# superpower.

🪜 Step by step

1. 🏗️ Class & constructor

The constructor has the same name as the class.

class Player
{
    public string Name { get; }
    public Player(string name) { Name = name; }
}
2. 🏷️ Properties

Properties look like fields but can control access.

public int Health { get; private set; } = 100;
3. ⚙️ Methods change state

Methods update properties safely.

public void TakeDamage(int amount)
{
    Health = Math.Max(0, Health - amount);
}

🧪 Try it!

Read the code, guess what it prints, then press 👀 Show output.

Player class

var p = new Player("Kai");
p.TakeDamage(30);
Console.WriteLine($"{p.Name}: {p.Health} HP, alive = {p.IsAlive}");
p.TakeDamage(200);
Console.WriteLine($"{p.Name}: {p.Health} HP, alive = {p.IsAlive}");

// In C#, classes go after the top-level statements.
class Player
{
    public string Name { get; }
    public int Health { get; private set; } = 100;
    public bool IsAlive => Health > 0;

    public Player(string name) => Name = name;

    public void TakeDamage(int amount) => Health = Math.Max(0, Health - amount);
}

Coin class

class Coin
{
    public int Value { get; set; } = 1;
}

📖 Key words

Tap a card to flip it over!

Property
A smart field with get/set 🏷️
Constructor
Builds a new object 🔨
private set
Only the class can change it 🔒
Computed property
A property calculated on demand 🧮

🏆 Challenge

Predict the output.

Challenge

var c = new Counter();
c.Tap(); c.Tap();
Console.WriteLine(c.Count);

class Counter
{
    public int Count { get; private set; }
    public void Tap() => Count++;
}

Knowledge Check Quiz

  1. What does { get; private set; } mean?
  2. Which keyword creates an object?
  3. What is IsAlive => Health > 0?
← Previous lesson
Next lesson →