Skip to content

Inside the Demo ​

You played Horde; this page walks through the code behind it. It shows how a frame is put together and then a handful of systems, each section picked for one KenseiECS idea, with the code taken straight from the game's sources. The whole game is in Demo/Game: components in Components.cs, wiring in HordeGame.cs, one file per system in Systems/.

How a frame runs ​

Everything systems share that is not a component (config, the spatial grid, the sprite buffer, the random generator) goes into one SharedData:

csharp
_shared = new SharedData();
_shared.Add(_config);
_shared.Add(_grid);
_shared.Add(_render);
_shared.Add(_rng);

The 22 systems are split into two named phases, sim and render, that hang off one root SystemsRunner. The gameplay systems sit in sim as one inline group, gameplay, so the game can pause them without touching the phase's own switch, which belongs to the inspector. The root owns SharedData. The demo calls only Warmup, which runs Init (cascading to both phases) and then pre-touches pools and filters so the first frames allocate less:

csharp
// Gameplay systems. Order matters: producers of events run before consumers,
// and the OneFrame types are removed after the last system.
_gameplay = new SystemsRunner(_world)
    .Add(new ClockSystem(), "clock")
    .Add(new PlayerMoveSystem(), "player-move")
    .Add(new WaveSpawnSystem(), "spawner")
    .Add(new GridBuildSystem(), "grid")
    .Add(new EnemySteerSystem(), "steer")
    .Add(new IntegrateSystem(), "integrate")
    .Add(new BoltWeaponSystem(), "bolt-fire")
    .Add(new BoltHitSystem(), "bolt-hit")
    .Add(new BladeSystem(), "blades")
    .Add(new NovaSystem(), "nova")
    .Add(_contact, "contact")
    .Add(new KnockbackSystem(), "knockback")
    .Add(new DamageSystem(), "damage")
    .Add(new LootSystem(), "loot")
    .Add(new MagnetSystem(), "magnet")
    .Add(new LevelUpSystem(), "level-up")
    .Add(new LifetimeSystem(), "lifetime")
    .OneFrame<EventBuffer<Hit>>()
    .OneFrame<Died>()
    .OneFrame<XpGained>();

// The sim phase holds them as one inline group. The game pauses by switching the
// group off (see SyncPause); the phase's own switch is left to the inspector.
_sim = new SystemsRunner(_world)
    .AddGroup("gameplay", _gameplay);

// Presentation phase, in draw order.
_renderPhase = new SystemsRunner(_world)
    .Add(new RenderGemsSystem(), "render-gems")
    .Add(new RenderEnemiesSystem(), "render-enemies")
    .Add(new RenderProjectilesSystem(), "render-projectiles")
    .Add(new RenderParticlesSystem(), "render-particles")
    .Add(new RenderPlayerSystem(), "render-player");

// Phases: Init cascades from the root,
// but each phase is driven explicitly with its own Run().
_root = new SystemsRunner(_world, _shared)
    .AddPhase("sim", _sim)
    .AddPhase("render", _renderPhase);

_root.Warmup();   // Init every system, then pre-touch pools and filters

Each frame the host calls HordeGame.Tick. Input and the frame time go into singletons on the game entity, then both phases run: render every frame, so the level-up screen still draws the frozen horde, and sim whenever time has passed. Because the phases are driven directly rather than through the root's Run, the host advances the tick with World.NextTick itself (nested runners), and only on a frame the game plays. A paused frame is not a simulation frame: steer alternates on the parity of the tick and the grid is simulation state, so both stay as the last played frame left them, and a run does not depend on how long a level-up screen stays open:

csharp
ref var input = ref _world.GetSingleton<PlayerInput>();
input.X = inputX;
input.Y = inputY;
_world.GetSingleton<GameState>().Dt = dt;

if (dt > 0f) {
    // A paused frame is not a simulation frame: the tick (steer alternates on its
    // parity) and the grid stay as the last played frame left them, so a run does
    // not depend on how long a level-up screen was open.
    if (_gameplay.IsEnabled) {
        _world.NextTick();   // only a root Run() ticks; phases are driven directly
        _grid.Clear();
    }
    _sim.Run();          // runs nothing while the gameplay group is switched off
    SyncPause();
}

RenderFrame();

The host does not look at the game status before it runs sim, and no system does either. Pausing a whole phase is the runner's job: on the level-up screen and at game over the host switches the gameplay group off with SetActive, and sim.Run() then runs no systems and keeps the group's OneFrame events until it runs again. The group's switch (IsEnabled) is also what the tick above asks before it advances. SyncPause is called after everything that can change the status: a sim run (a level-up, a death), ChooseUpgrade and Restart.

csharp
// The level-up screen and game over pause the run. Pausing a whole phase is the
// runner's job: the gameplay group is switched off with SetActive, and no system
// checks Status. Called after everything that can change Status: a sim run
// (level-up, death), ChooseUpgrade and Restart.
private void SyncPause() {
    _gameplay.SetActive(_world.GetSingleton<GameState>().Status == GameStatus.Playing);
}

Inside the systems the same idea is a tag and a filter (rule 1 for AI agents): contact tags a dead player with Dead, and level-up offers upgrades only through an [Exc(typeof(Dead))] filter, so a death and a level-up in the same frame end the run; spawner lays a swarm down only while a Swarm component exists.

Try it in the demo: open the inspector (` or the ECS button) and untick the render phase. The sprites disappear while the simulation and the camera keep going.

integrate: an owning group ​

In the game: moves everything that has a velocity: the player, every enemy, bolts, gems flying to the player, sparks. With 20,000 entities on screen this is the loop that has to be cheap.

The idea: an owning Group<Position, Velocity>. The group keeps the dense arrays of both pools aligned, so entity i of the group is at index i in both. The loop walks two plain spans, with no filter and no sparse lookups. [Group] is filled by the generated Init.

csharp
[Group] private Group<Position, Velocity> _moving;

public void Run(World world) {
    float dt = world.GetSingleton<GameState>().Dt;
    var positions = _moving.Data1;
    var velocities = _moving.Data2;
    for (int i = 0; i < positions.Length; i++) {
        ref var p = ref positions[i];
        ref readonly var v = ref velocities[i];
        p.X += v.X * dt;
        p.Y += v.Y * dt;
    }
}

Membership follows the components: when magnet adds a Velocity to a gem, the gem joins the group and integrate starts moving it, with no change to this system.

Try it in the demo: untick integrate. The horde and the player freeze: only integrate turns velocity into movement. Blades and the nova ring, which are placed directly, keep going.

bolt-fire: structural changes through a CommandBuffer ​

In the game: whenever the cooldown is up, fires a volley of bolts at the nearest enemy.

The idea: the system creates entities while it iterates the _shooters filter. Calling World.CreateEntity inside the loop would be safe here: the iteration contract allows creating entities in a foreach, and new bolts would not match _shooters anyway. The system records the spawns in a CommandBuffer instead to batch them: all of them are applied in one Playback after the loop. CreateEntity on the buffer returns a PendingEntity that later Add commands of the same buffer can target, so several components can be added to an entity that does not exist yet. The buffer is a field: one buffer per system, which stops allocating once its capacity has settled. A buffer becomes necessary when a loop changes other entities, ones the iteration has not visited yet.

csharp
private readonly CommandBuffer _buffer = new();

public void Run(World world) {
    float dt = world.GetSingleton<GameState>().Dt;
    foreach (int e in _shooters) {
        ref var weapon = ref _weapons.Get(e);
        ref var player = ref _players.Get(e);
        weapon.Timer -= dt;
        if (weapon.Timer > 0f) {
            continue;
        }

        var p = _positions.Get(e);
        int target = _grid.Nearest(p.X, p.Y, _config.BoltRange);
        if (target < 0) {
            weapon.Timer = 0f;   // stay ready until something is in range
            continue;
        }
        weapon.Timer = weapon.Cooldown * player.CooldownMul;

        float aim = MathF.Atan2(_grid.Y[target] - p.Y, _grid.X[target] - p.X);
        const float spread = 0.13f;
        for (int k = 0; k < weapon.Count; k++) {
            float a = aim + (k - (weapon.Count - 1) * 0.5f) * spread;
            var bolt = _buffer.CreateEntity(new Bolt {
                Damage = weapon.Damage * player.DamageMul,
                PierceLeft = weapon.Pierce   // LastHit = default: Entity.Null
            });
            _buffer.Add(bolt, new Position { X = p.X, Y = p.Y });
            _buffer.Add(bolt, new Velocity { X = MathF.Cos(a) * _config.BoltSpeed, Y = MathF.Sin(a) * _config.BoltSpeed });
            _buffer.Add(bolt, new Radius { Value = _config.BoltRadius });
            _buffer.Add(bolt, new Lifetime { Left = _config.BoltLife, Total = _config.BoltLife });
        }
    }
    _buffer.Playback(world);
}

loot uses the same pattern for the opposite change: while iterating the dead enemies it records the gem, the sparks and the DestroyEntity of the enemy, then plays the buffer back once after the loop.

Try it in the demo: untick bolt-fire. No new bolts appear; the ones already in flight finish their path. Untick loot instead and enemies keep taking hits but nothing dies or drops gems.

bolt-hit → damage + knockback: events with two consumers ​

In the game: a bolt that touches an enemy deals damage and pushes the enemy back. One enemy can be hit by several bolts, a blade and the nova in the same frame.

The idea: a plain component holds one value per entity, so hits are collected in an EventBuffer<Hit> with world.AddEvent, which appends any number of events to an entity in one frame (several events per entity). bolt-hit, blades, nova and contact all produce Hit events; contact sends zero-damage hits that only carry knockback.

Inside bolt-hit, the loop walks the spatial grid g around each bolt; every enemy j that overlaps the bolt gets a Hit, with knockback along the bolt's velocity v:

csharp
var target = world.GetEntity(g.Entity[j]);
if (target == bolt.LastHit) {
    continue;
}
world.AddEvent(target, new Hit {
    Damage = bolt.Damage, KnockX = v.X * 0.25f, KnockY = v.Y * 0.25f
});
bolt.LastHit = target;

Two systems read the same events and know nothing about each other or about the producers. damage sums the damage and marks the dead with Died:

csharp
[Inc(typeof(EventBuffer<Hit>), typeof(Health), typeof(Enemy))] private Filter _hit;
[Pool] private ComponentPool<EventBuffer<Hit>> _hits;
[Pool] private ComponentPool<Health> _health;
[Pool] private ComponentPool<Enemy> _enemies;
[Pool] private ComponentPool<Died> _died;

public void Run(World world) {
    foreach (int e in _hit) {
        var events = _hits.Get(e).Values;
        float total = 0f;
        for (int i = 0; i < events.Count; i++) {
            total += events[i].Damage;
        }
        if (total <= 0f) {
            continue;
        }
        ref var hp = ref _health.Get(e);
        _enemies.Get(e).Flash = 1f;
        hp.Value -= total;
        if (hp.Value <= 0f && !_died.Has(e)) {
            _died.Add(e, new Died());
        }
    }
}

knockback adds up the push, but only for light enemies: tanks and elites carry the Heavy tag, and the [Exc] filter simply leaves them out:

csharp
[Inc(typeof(EventBuffer<Hit>), typeof(Enemy))] [Exc(typeof(Heavy))] private Filter _hitLight;
[Pool] private ComponentPool<EventBuffer<Hit>> _hits;
[Pool] private ComponentPool<Enemy> _enemies;

public void Run(World world) {
    foreach (int e in _hitLight) {
        var events = _hits.Get(e).Values;
        ref var enemy = ref _enemies.Get(e);
        for (int i = 0; i < events.Count; i++) {
            var hit = events[i];
            enemy.KnockX += hit.KnockX;
            enemy.KnockY += hit.KnockY;
        }
    }
}

When they are cleared: EventBuffer<Hit>, Died and XpGained are registered as OneFrame on the gameplay group, the runner inside the sim phase that holds the gameplay systems. The group removes them at the end of its Run, after lifetime, the last system, so every consumer between the producers and the end of the group sees them, and nobody sees them the next frame. The pooled event lists are recycled, not reallocated. This is why the order in the runner matters: producers first, consumers after them.

csharp
.OneFrame<EventBuffer<Hit>>()
.OneFrame<Died>()
.OneFrame<XpGained>();

Try it in the demo: untick knockback. Hits still kill, but light enemies are no longer shoved back. Untick damage instead: bolts still hit and push enemies, but nothing dies.

player-move: a generated Init ​

In the game: turns the input singleton into the player's velocity; integrate does the actual moving.

The idea: the system is a partial class with marked fields and no Init. The source generator writes Init for it: the [Inc] field gets a filter built with world.Filter(), each [Pool] field gets world.Pool<T>(), and the runner calls the generated Init like any hand-written one.

csharp
public partial class PlayerMoveSystem : IRunSystem {
    [Inc(typeof(Player), typeof(Velocity))] private Filter _player;
    [Pool] private ComponentPool<Player> _players;
    [Pool] private ComponentPool<Velocity> _velocities;

    public void Run(World world) {
        ref var input = ref world.GetSingleton<PlayerInput>();
        foreach (int e in _player) {
            float speed = _players.Get(e).Speed;
            ref var v = ref _velocities.Get(e);
            v.X = input.X * speed;
            v.Y = input.Y * speed;
        }
    }
}

[Shared] fields are filled the same way from the runner's SharedData. grid, for example, receives the spatial grid and the config it was given in How a frame runs:

csharp
[Inc(typeof(Enemy), typeof(Position), typeof(Radius))] private Filter _enemies;
[Pool] private ComponentPool<Enemy> _enemyData;
[Pool] private ComponentPool<Position> _positions;
[Pool] private ComponentPool<Radius> _radii;
[Shared] private SpatialGrid _grid;
[Shared] private GameConfig _config;

Try it in the demo: hold a direction and untick player-move while moving. The player keeps drifting the same way: Velocity was last written by player-move, and integrate keeps applying it.

Things worth stealing ​

  • Entity handles, not int indices, for stored references. Bolt.LastHit remembers the enemy a piercing bolt hit last, across frames. It is an Entity: an int index could name a newer enemy once the slot is reused. Indices are fine within the current iteration. See handles vs. indices.
  • A spatial grid as a shared service. SpatialGrid is a plain class in SharedData, rebuilt once a frame by grid with a counting sort and queried by steer, bolt-fire, bolt-hit, blades, nova and contact. It stores a copy of each enemy's position and radius, so neighbour queries never touch the component pools.
  • Zero allocations in steady state. Capacities are set up front in WorldConfig, Warmup pre-touches pools and filters, every system keeps its own CommandBuffer, and events reuse pooled lists. Once pool, filter and buffer capacities have settled, a frame allocates nothing; Demo/Headless measures it.
  • Recycle instead of destroy and create. Enemies and gems left far behind are moved ahead of the player instead of being destroyed and spawned again (GridBuildSystem.cs, MagnetSystem.cs).
  • One system, one idea. Each of the 22 systems is short and does one thing, so any of them can be switched off live from the inspector to see what it does. The system table lists the feature each one shows.