TExcelTAD
Home › Unity with C# › ECS: Entities & Systems

ECS: Entities & Systems

GameObjects are flexible but heavy: each one is a managed object with a Transform, a list of components and virtual message calls, scattered around memory. That's fine for hundreds of objects. For tens of thousands (crowds, bullets, asteroid fields, RTS units), Unity offers DOTS, the Data-Oriented Technology Stack:

  • Entities (com.unity.entities): an Entity Component System (ECS).
  • Jobs: safe multithreading. See Jobs & Burst.
  • Burst: a compiler that turns a subset of C# into highly optimized native code.

The three ideas

ECS term Meaning GameObject equivalent
Entity just an id a GameObject, without the object
Component a plain struct of data (IComponentData), no behaviour the fields of a MonoBehaviour
System code that runs over every entity that has a given set of components the Update methods, but one per behaviour instead of one per object

Entities with the same set of component types share an archetype, and their components are stored in tightly packed arrays in 16 KB chunks. A system that moves things reads two arrays from start to end, which is what CPUs are fastest at.

A mini ECS in plain C#

The model stores components in arrays per archetype, runs a query, and defers structural changes (destroying entities) to a command buffer, as Unity's ECS does:

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

var world = new World();
// Archetype A: Position + Velocity. Archetype B: Position + Velocity + Health.
for (int i = 0; i < 4; i++) world.Movers.Add(new Position(i, 0), new Velocity(1, 0.5f * i));
for (int i = 0; i < 3; i++) world.Units.Add(new Position(0, i), new Velocity(0, 1), new Health(10 * (i + 1)));

for (int frame = 1; frame <= 3; frame++)
{
    float dt = 1f;
    MoveSystem.Run(world, dt);           // query: Position + Velocity (both archetypes)
    PoisonSystem.Run(world, 12);         // query: Health (archetype B only)
    world.Playback();                    // apply structural changes at a sync point
    Console.WriteLine(
quot;frame {frame}: movers {world.Movers.Count}, units {world.Units.Count}, first mover {world.Movers.Pos[0]}, units hp [{world.Units.HpList()}]"); } record struct Position(float X, float Y) { public override string ToString() =>
quot;({X:F1}, {Y:F1})"; } record struct Velocity(float X, float Y); record struct Health(int Value); class MoverChunk // archetype: Position + Velocity (struct arrays) { public Position[] Pos = new Position[16]; public Velocity[] Vel = new Velocity[16]; public int Count; public void Add(Position p, Velocity v) { Pos[Count] = p; Vel[Count] = v; Count++; } } class UnitChunk // archetype: Position + Velocity + Health { public Position[] Pos = new Position[16]; public Velocity[] Vel = new Velocity[16]; public Health[] Hp = new Health[16]; public int Count; public void Add(Position p, Velocity v, Health h) { Pos[Count] = p; Vel[Count] = v; Hp[Count] = h; Count++; } public void RemoveAtSwapBack(int i) { Count--; Pos[i] = Pos[Count]; Vel[i] = Vel[Count]; Hp[i] = Hp[Count]; } // keep arrays packed public string HpList() { var s = new List<string>(); for (int i = 0; i < Count; i++) s.Add(Hp[i].Value.ToString()); return string.Join(", ", s); } } class World { public MoverChunk Movers = new(); public UnitChunk Units = new(); readonly List<int> toDestroy = new(); // an "EntityCommandBuffer" public void DestroyUnitLater(int index) => toDestroy.Add(index); public void Playback() { toDestroy.Sort(); toDestroy.Reverse(); // remove from the back so indices stay valid foreach (int i in toDestroy) Units.RemoveAtSwapBack(i); toDestroy.Clear(); } } static class MoveSystem { public static void Run(World w, float dt) { Move(w.Movers.Pos, w.Movers.Vel, w.Movers.Count, dt); Move(w.Units.Pos, w.Units.Vel, w.Units.Count, dt); } static void Move(Position[] pos, Velocity[] vel, int count, float dt) { for (int i = 0; i < count; i++) // linear walk over packed arrays pos[i] = new Position(pos[i].X + vel[i].X * dt, pos[i].Y + vel[i].Y * dt); } } static class PoisonSystem { public static void Run(World w, int damage) { for (int i = 0; i < w.Units.Count; i++) { w.Units.Hp[i] = new Health(w.Units.Hp[i].Value - damage); if (w.Units.Hp[i].Value <= 0) w.DestroyUnitLater(i); // can't remove while iterating } } }
frame 1: movers 4, units 2, first mover (1.0, 0.0), units hp [18, 8]
frame 2: movers 4, units 1, first mover (2.0, 0.0), units hp [6]
frame 3: movers 4, units 0, first mover (3.0, 0.0), units hp []

Real ECS adds automatic archetype management, change tracking, chunk iteration in parallel jobs and Burst compilation, but the shape is the same: data in arrays, logic in systems, structural changes deferred.

The same in Unity Entities

Components and a system (Entities 1.x):

csharp
using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

public struct Velocity : IComponentData { public float3 Value; }
public struct Health : IComponentData { public int Value; }

[BurstCompile]
public partial struct MoveSystem : ISystem
{
    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        float dt = SystemAPI.Time.DeltaTime;
        foreach (var (transform, velocity) in
                 SystemAPI.Query<RefRW<LocalTransform>, RefRO<Velocity>>())
        {
            transform.ValueRW.Position += velocity.ValueRO.Value * dt;
        }
    }
}

Entities are usually authored as normal GameObjects in a SubScene and converted by bakers:

csharp
using Unity.Entities;
using UnityEngine;

public class AsteroidAuthoring : MonoBehaviour
{
    public Vector3 velocity;
    public int health = 30;

    class Baker : Baker<AsteroidAuthoring>
    {
        public override void Bake(AsteroidAuthoring authoring)
        {
            Entity entity = GetEntity(TransformUsageFlags.Dynamic);
            AddComponent(entity, new Velocity { Value = authoring.velocity });
            AddComponent(entity, new Health { Value = authoring.health });
        }
    }
}

Destroying entities from inside a query goes through an EntityCommandBuffer (for example from SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>()), the same deferred-change idea as the model.

Is it worth it?

Use DOTS when Stay with GameObjects when
thousands of similar things simulate every frame most objects are unique and few
the Profiler shows the CPU is the bottleneck in that simulation you're still prototyping the game design
the team can invest in a different workflow you rely on Asset Store tools that expect GameObjects

A popular middle path: keep the game in GameObjects and use Jobs + Burst alone for the heavy loops (the next lesson). Rendering, physics (Unity Physics or Havok for ECS), animation and networking (Netcode for Entities) all have ECS counterparts, but check their maturity for your needs before committing.

Test yourself

In ECS, where does behaviour live?

  1. In components
  2. In systems that run over entities with matching components
  3. In the entity
  4. In MonoBehaviours only

What is an archetype?

  1. A prefab variant
  2. The unique set of component types an entity has; entities with the same set are stored together
  3. A system group
  4. A Burst setting

Why are entity destructions recorded in a command buffer during iteration?

  1. To log them
  2. Structural changes would move data the query is iterating; they're applied at a safe sync point
  3. Entities can never be destroyed
  4. Burst requires it