TExcelTAD
Home › Game Development Roadmap & Fundamentals › Entities & Components

Entities & Components

A game world is full of things: the player, enemies, bullets, doors, coins, the camera. Programmers call them entities (Unity says GameObjects, Unreal says Actors, Godot says nodes). The interesting question is how to give them behavior without drowning in special cases. The answer most engines settled on is composition: an entity is a container, and components give it abilities.

Why deep inheritance breaks

The first instinct from object-oriented programming is a class tree:

text
Entity
 ├─ Character
 │   ├─ Player
 │   └─ Enemy
 │       ├─ FlyingEnemy
 │       └─ ShootingEnemy
 └─ Prop
     └─ ExplodingBarrel

Then the designer asks for a flying enemy that shoots. Or an exploding barrel that can be picked up, like the player picks up items. Or a turret: it shoots like an enemy but can't move. Each request either duplicates code or pushes features up into Entity until every object carries every ability. This is the classic "diamond" or "god class" problem.

Composition: has-a instead of is-a

Give each ability its own small component, and build entities by picking components:

Entity Components
Player Position, Velocity, Health, PlayerInput, Shooter
Flying shooting enemy Position, Velocity, Health, Flyer, Shooter, EnemyAI
Turret Position, Health, Shooter, EnemyAI
Exploding barrel Position, Health, ExplodeOnDeath, Pickup

A new kind of thing is a new combination, not a new class.

csharp · try it yourself
using System;
using System.Collections.Generic;

var world = new List<Entity>
{
    new Entity("player").With(new Health(100)).With(new Shooter(Damage: 10)),
    new Entity("turret").With(new Health(40)).With(new Shooter(Damage: 4)),
    new Entity("barrel").With(new Health(5)).With(new ExplodeOnDeath(Radius: 3)),
    new Entity("coin"),
};

foreach (var e in world)
{
    var parts = new List<string>();
    if (e.Get<Health>() is Health h) parts.Add(
quot;health {h.Current}"); if (e.Get<Shooter>() is Shooter s) parts.Add(
quot;shoots for {s.Damage}"); if (e.Get<ExplodeOnDeath>() is ExplodeOnDeath x) parts.Add(
quot;explodes (r={x.Radius})"); Console.WriteLine(
quot;{e.Name,-7}: {(parts.Count > 0 ? string.Join(", ", parts) : "no components")}"); } class Entity { public string Name { get; } readonly Dictionary<Type, object> components = new(); public Entity(string name) => Name = name; public Entity With(object component) { components[component.GetType()] = component; return this; } public T Get<T>() where T : class => components.TryGetValue(typeof(T), out var c) ? (T)c : null; } record Health(int Current); record Shooter(int Damage); record ExplodeOnDeath(int Radius);
player : health 100, shoots for 10
turret : health 40, shoots for 4
barrel : health 5, explodes (r=3)
coin   : no components

Systems: behavior that works on components

Where does the logic live? Two styles exist, and engines use both:

  1. Components with behavior (Unity MonoBehaviours, Unreal ActorComponents, Godot node scripts): each component has its own update method.
  2. Entity Component System (ECS): components are plain data, and systems loop over every entity that has a given set of components. Unity's Entities package (DOTS), the C++ libraries EnTT and flecs, and the Bevy engine (Rust) work this way.

Here is a tiny ECS-style world. Components live in dictionaries keyed by entity id; the movement system touches only entities with both a position and a velocity, and the lifetime system removes expired bullets:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var positions = new Dictionary<int, (double X, double Y)>();
var velocities = new Dictionary<int, (double X, double Y)>();
var lifetimes = new Dictionary<int, double>();
var names = new Dictionary<int, string>();
int nextId = 1;

int Spawn(string name) { names[nextId] = name; return nextId++; }

int player = Spawn("player");
positions[player] = (0, 0); velocities[player] = (1, 0);
int tree = Spawn("tree");
positions[tree] = (5, 2);                                  // no velocity: never moves
int bullet = Spawn("bullet");
positions[bullet] = (0, 0); velocities[bullet] = (8, 0); lifetimes[bullet] = 0.25;

const double dt = 0.1;
for (int tick = 1; tick <= 3; tick++)
{
    // movement system: every entity with Position AND Velocity
    foreach (int id in velocities.Keys.Where(positions.ContainsKey).ToList())
        positions[id] = (positions[id].X + velocities[id].X * dt, positions[id].Y + velocities[id].Y * dt);

    // lifetime system: every entity with a Lifetime
    foreach (int id in lifetimes.Keys.ToList())
    {
        lifetimes[id] -= dt;
        if (lifetimes[id] <= 0) { Destroy(id); Console.WriteLine(
quot; tick {tick}: {names[id]} expired"); } } var row = positions.OrderBy(p => p.Key).Select(p =>
quot;{names[p.Key]}({p.Value.X:F1},{p.Value.Y:F1})"); Console.WriteLine(
quot;tick {tick}: {string.Join(" ", row)}"); } void Destroy(int id) { positions.Remove(id); velocities.Remove(id); lifetimes.Remove(id); }
tick 1: player(0.1,0.0) tree(5.0,2.0) bullet(0.8,0.0)
tick 2: player(0.2,0.0) tree(5.0,2.0) bullet(1.6,0.0)
  tick 3: bullet expired
tick 3: player(0.3,0.0) tree(5.0,2.0)

The tree never moves because the movement system never sees it, with no if (canMove) anywhere. Adding "the tree is blown by wind" means adding a Velocity component, not changing code.

How the engines do it

Engine Entity Component Logic lives in
Unity GameObject (+ Transform) MonoBehaviour and built-ins (Rigidbody, Collider) the components' Update() methods; DOTS adds a real ECS
Unreal AActor UActorComponent, USceneComponent actor and component Tick(), plus the gameplay framework classes
Godot Node in a scene tree child nodes (a CollisionShape2D under a CharacterBody2D) the node scripts' _process() / _physics_process()

Godot's twist: instead of components on an entity, you compose nodes into scenes, and scenes nest inside other scenes. The idea is the same: small parts, combined.

Rules of thumb

  • Prefer small components that each do one thing ("Health", "Damageable", "Pickup").
  • Components talk through events or a shared entity, not by knowing each other's concrete types (see Game Events).
  • Inheritance is still fine for a shallow hierarchy inside one concept (Weapon → Sword, Bow).
  • Use a full ECS when you have thousands of similar objects and need the performance; for most games, the engine's normal components are the right tool.

Test yourself

What is the main problem with a deep entity inheritance tree?

  1. It uses too much memory
  2. New combinations of abilities don't fit the tree, causing duplicated code or bloated base classes
  3. C# doesn't allow inheritance
  4. It is slower to compile

In an ECS, what is a system?

  1. A component with data
  2. A function that processes every entity having a given set of components
  3. The operating system
  4. A type of entity

In the ECS example, why does the tree never move?

  1. Its speed is zero
  2. It has no Velocity component, so the movement system skips it
  3. It is destroyed
  4. Trees are static in C#