Component-Based Entity System
Moving away from deep inheritance hierarchies toward flat, data-only components, JSON entity definitions, and decoupled systems in C#.
At the start of a game project, it's easy to think of entities in your game as "kinds of things", but at some point, you want unrelated entities to share the same behaviour.
Consider the following:
classDiagram
Entity <|-- Ship
Entity <|-- Projectile
Projectile <|-- Missile
Ship <|-- Cruiser
class Entity {
+Id
}
class Projectile {
+Damage
}
class Cruiser {
+ShootMissile()
} Cruisers can shoot missiles, great. What if we also want a missile tower?
classDiagram
Entity <|-- Building
Entity <|-- Ship
Entity <|-- Projectile
Projectile <|-- Missile
Ship <|-- Cruiser
Building <|-- MissileTower
class Entity {
+Id
}
class Projectile {
+Damage
}
class Cruiser {
+ShootMissile()
}
class MissileTower {
+ShootMissile()
} The first time this happens, we'll probably copy the missile shooting logic. If there's enough desire, maybe we add a helper class to launch missiles for us. Not great.
I, like many others, used a "component based system", called by many names: behaviour-based system, entity-component-system, etc. Any way you call it, there are two main parts:
- Components store data.
- Systems operate on components.
Let's look at the same example, but with components:
classDiagram
Component <|-- Position
Component <|-- Velocity
Component <|-- Animator
Component <|-- Projectile
Component <|-- ProjectileLauncher
class Component {
+EntityId
}
class Projectile {
+Damage
+Thrust
}
class ProjectileLauncher {
+ProjectileType
+FireRate
}
class Position {
+X
+Y
}
class Velocity {
+X
+Y
}
class Animator {
+Sprite
+Rotation
} classDiagram
ISystem <|-- ProjectileSystem
ISystem <|-- ProjectileLauncherSystem
ISystem <|-- AnimationSystem
ISystem <|-- PhysicsSystem
class ISystem {
+Update()
}
First thing to note is that the hierarchy is flat, and there are no more "kinds"
of entities. Entities are now just a collection of components and their values.
The Component class only has one property: EntityId.
For example, the "Cruiser" from before can be strictly data describing the
components that make up a "Cruiser":
{
"Position": { "EntityId": 1, "X": 100, "Y": 100 },
"Velocity": { "EntityId": 1, "X": 0, "Y": 0 },
"Animator": { "EntityId": 1, "Sprite": "cruiser.png", "Rotation": 180 },
"ProjectileLauncher": { "EntityId": 1, "ProjectileType": "Missile", "FireRate": 1 }
}
There is no "entity" object anymore—instead, it's a collection of the components
that make up the entity. You can look up all components belonging to an entity
via its EntityId.
Let's talk about systems
This is a space game, so my physics were pretty basic, but my PhysicsSystem loops over all velocity components and adds any
velocity to the position for the matching EntityId.
The AnimationSystem does two things: it updates and it renders.
Each update, it loops over all Animator components and advances the
animation. Each render, it uses the Position component to draw the
sprite at the appropriate location. Animators without a Position
component are invalid and can't be rendered anywhere.
The ProjectileLauncherSystem loops over ProjectileLauncher components and determines if a new projectile
should be created. If so, it makes a new EntityId and builds out
the appropriate components:
{
"Position": { "EntityId": 2, "X": 100, "Y": 100 },
"Velocity": { "EntityId": 2, "X": 0, "Y": 0 },
"Animator": { "EntityId": 2, "Sprite": "missile.png", "Rotation": 120 },
"Projectile": { "EntityId": 2, "Damage": 10, "Thrust": 10 }
}
The ProjectileSystem adds the Thrust to the Velocity, detects a collision with a valid target, and boom.
Many components make short work
-
The
ProjectileLauncherSystemdecides when to make newProjectiles, with a position matching thePositionof the launcher. -
The
ProjectileSystemadds theProjectile'sThrustto theVelocityin the direction of its target. -
The
PhysicsSystemadds theVelocityto thePosition. -
The
AnimationSystemupdates theAnimatorand renders the sprite at the entity'sPosition.
To have a building that can launch missiles, you just add the ProjectileLauncher component to a building (no velocity component
needed for stationary objects):
{
"Position": { "EntityId": 3, "X": 500, "Y": 500 },
"Animator": { "EntityId": 3, "Sprite": "missileTower.png", "Rotation": 0 },
"ProjectileLauncher": { "EntityId": 3, "ProjectileType": "Missile", "FireRate": 1 }
} Flexibility
Components can be added or removed on the fly for particle effects or temporary
buffs/banes—just add a component/system pair for slow, poison, fire, or even a
scenario-specific Tornado component.
Some components and systems I built for Asteroid Outpost:
-
An
EntityNamecomponent for human-readable debugging names. - Unique component/system pairs for scenario-specific structures or events.
- Particle effect component/system for smoke trails and explosions (supporting multiple instances per entity).
- An auto-healing component/system pair that restores hit points over time.
- Power grid components (producers, consumers, storage) with systems managing power flow.
- A frame-rate counting system.
Implementation Overview
Entity definitions lived in JSON template files like:
{
"Name": "Asteroid",
"Components": {
"EntityName": { "Name": "Asteroid" },
"Position": { "Solid": false },
"Minable": { "Minerals": "**", "StartingMinerals": "**" },
"Animator": { "SpriteName": "Asteroid", "Scale": "**", "CurrentAnimation": "Idle" },
"Selectable": {}
}
}
All component names matched a C# component class name exactly, and any "**" values were required to be filled in at runtime (failing fast
if any remained after merging the template with runtime data). Components were
indexed in two dictionaries for fast lookup:
-
Dictionary<int, List<IComponent>> entityDictionary;— all components for an entity ID. -
Dictionary<Type, List<IComponent>> componentDictionary;— all components of a given type.
For example, my auto-heal system looked like this:
public override void Update(GameTime gameTime)
{
if (world.Paused) { return; }
foreach (var autoHealer in world.GetComponents<AutoHeal>())
{
autoHealer.TimeSinceLastHit += gameTime.ElapsedGameTime;
if (autoHealer.TimeSinceLastHit.TotalSeconds >= autoHealer.Delay)
{
var hitPoints = world.GetComponent<HitPoints>(autoHealer);
if (hitPoints.Armour < hitPoints.TotalArmour)
{
hitPointSystem.Heal(
hitPoints,
autoHealer.Rate * (float)gameTime.ElapsedGameTime.TotalSeconds
);
}
}
}
base.Update(gameTime);
}