Skip to content

Quick Start ​

A complete console program: two components, one system that moves every entity with a Position and a Velocity, and a runner that drives it. It runs as-is on .NET once the project references KenseiECS (see Installation).

csharp
using System;
using KenseiECS;

struct Position : IComponent { public float X, Y; }
struct Velocity : IComponent { public float X, Y; }

class MovementSystem : IInitSystem, IRunSystem {
    Filter _filter;
    ComponentPool<Position> _positions;
    ComponentPool<Velocity> _velocities;

    public void Init(World world, SharedData shared) {
        _filter = world.Filter().Inc<Position>().Inc<Velocity>().End();
        _positions = world.Pool<Position>();
        _velocities = world.Pool<Velocity>();
    }

    public void Run(World world) {
        foreach (int e in _filter) {
            ref var pos = ref _positions.Get(e);
            ref var vel = ref _velocities.Get(e);
            pos.X += vel.X;
            pos.Y += vel.Y;
        }
    }
}

static class Program {
    static void Main() {
        var world = new World();
        var systems = new SystemsRunner(world)
            .Add(new MovementSystem());

        systems.Init();

        var entity = world.CreateEntity(new Position());
        world.Add(entity, new Velocity { X = 1, Y = 2 });
        systems.Run();

        ref var pos = ref world.Get<Position>(entity);
        Console.WriteLine($"Position: ({pos.X}, {pos.Y})");   // Position: (1, 2)

        systems.Destroy();
    }
}

Output:

Position: (1, 2)

What happens here ​

  1. Components are plain structs implementing IComponent. See Components.
  2. The system builds a filter and caches the two pools in Init, then walks the filter in Run. The filter yields int entity indices; ComponentPool<T>.Get returns the component by ref, so the writes land in the pool. See Filters and Systems.
  3. The runner calls Init once, Run every frame and Destroy on shutdown. See SystemsRunner.
  4. The entity is created with its first component; an entity always has at least one. See Entities.

In Unity, derive from EcsBootstrap instead of writing Main: it owns the world and drives the runners from Update, FixedUpdate and LateUpdate. See Bootstrap & Authoring.

TIP

Writing Init by hand is optional: mark the fields and let the source generator fill them.