Manual

Manual

Systems and schedules

This page goes further than Entities, components and systems and C# in a game: how a system declares its query and reads it, the order systems run in, systems at a fixed rate and on every core, what happens when one fails, how systems change what exists while the game plays, and how they read events.

Two ways to add a system

A plugin's Build adds systems to the schedule it is given. A system is added either from a method's signature or by hand.

From a method's signature

Mark a static method [AbyssSystem] in a partial type, and the build writes an Add method for it, named after it: AddFall for a method Fall. Its parameters are the schedule, a component type for each component the system touches and a resource type for each resource, in the order of the method's parameters, then three optional ones:

public static partial class Falling{    [AbyssSystem(Fixed = true)]    [MethodImpl(MethodImplOptions.AggressiveInlining)]    private static void Fall(ref Velocity velocity, Res<Gravity> gravity, in SystemContext context)    {        velocity.Y -= gravity.Value.Strength * context.DeltaTime;    }}
// In a plugin's Build. The generated method is:// AddFall(Schedule schedule, ComponentType<Velocity> velocity, ResourceType<Gravity> gravity,//         ReadOnlySpan<QueryFilter> filters = default, bool? markChanged = null,//         StructuralAccess structural = default)SystemId fall = Falling.AddFall(schedule, world.Component<Velocity>(), world.Resource<Gravity>());

The parameters a method may take are listed in Writing a system. The attribute has three settings:

SettingWhat it does
NameThe name the Logs panel and the Profiler show for the system. Without it, the type's name and the method's, Falling.Fall.
FixedRuns the system at the game's fixed rate; see Systems at a fixed rate.
ParallelCuts the system's loop into slices that several threads run; see One system on every core.

The build refuses a signature the engine cannot run, at the method:

CodeWhat it refuses
ABYSS001A system method that is not static.
ABYSS002A type holding a system, or any type around it, that is not partial.
ABYSS003The same component twice in one signature.
ABYSS004A component that is not an unmanaged struct.
ABYSS005Per-entity parameters (ref T, in T) mixed with per-chunk ones (Span<T>, ReadOnlySpan<T>).
ABYSS006A parameter of any other form.
ABYSS007A generic system method.
ABYSS008A system that touches no component and no resource.
ABYSS009A system method that returns a value.
ABYSS010A warning: a per-entity system without [MethodImpl(MethodImplOptions.AggressiveInlining)], which runs several times slower.
ABYSS016 to ABYSS018What a parallel system cannot do; see One system on every core.

By hand

schedule.Add takes a name, the components the system reads and writes, and a body that receives the SystemContext. Three forms add filters and resources:

schedule.Add(name, terms, body);schedule.Add(name, terms, filters, body);schedule.Add(name, terms, filters, resources, body);   // pass default for no filters

Each takes markChanged and structural after the body. Write a system by hand when it needs the ids of the entities it reads, a loop over chunks of its own, or a parallel loop with its own slice size. Make the body a static lambda when it uses nothing from around it, so nothing is captured.

Both ways return a SystemId, which is what ordering takes.

Queries

A system's query is the list of components it touches, each read or written, and its filters. The schedule runs the system over every entity that carries all of those components and passes its filters.

Read and write

Each component is a term: transform.Read() or transform.Write(), from the ComponentType<T> that world.Component<T>() or world.Transform() gives. A written column is a Span<T> from chunk.GetSpan<T>, and a read one a ReadOnlySpan<T> from chunk.GetReadOnlySpan<T>. Asking for a writable span of a column declared as read throws.

The engine trusts what a system declares: which change ticks it publishes, and which systems may share a column, follow from it. The [AbyssSystem] form takes the declaration from ref and in, so it cannot disagree with what the body does.

Filters

A filter narrows the query by a component without giving the system a column of it. With() keeps the entities that carry the component, and Without() the ones that do not:

ComponentType<Player> player = world.Component<Player>();ComponentType<Enemy> enemy = world.Component<Enemy>();
schedule.Add("Move players", [transform.Write()], [player.With()], MovePlayers);schedule.Add("Move enemies", [transform.Write()], [enemy.With(), player.Without()], MoveEnemies);

A generated Add takes filters as its filters argument: Moving.AddDrift(schedule, transform, drift, filters: [player.Without()]).

Some entities are seen by no query at all: an entity switched off with the checkbox in its Inspector header, or by world.SetActive(entity, false), together with everything under it, and the entities of a scene that is still loading.

Reacting to changes

A C# query has no filter for components that changed or were just added: each frame, a system sees every entity that matches. To act once on something new, give it a component that marks it, with a command, and take the mark away once a system has handled it.

What C# writes reaches Bevy's change detection where something in Rust may be watching. A system that writes a component with a Rust type, such as Transform, a Bevy component or a plugin's, publishes Bevy's change ticks for what it wrote, so Bevy's transform propagation and a Rust system with Changed<T> see the write. That is what markChanged decides, and it is on by itself for those systems. It costs a write for each entity of each written column. Pass markChanged: false only where nothing in Rust watches, and never for a system that moves a Transform: without the ticks, the entity stops moving after the first frame.

Chunks, rows and columns

context.Chunks is the query's result: a chunk for each table of entities with the same components, as described in Components. In a chunk:

MemberWhat it is
CountHow many entities, or rows, the chunk has.
EntitiesThe entity of each row, as a ReadOnlySpan<ulong>, in the same order as every column.
GetSpan<T>(column)A written column, straight over the engine's memory: writing to it writes the component.
GetReadOnlySpan<T>(column)A read column.
GetFieldView<T>(column, field)One field of a component with a Rust type; see Components from Rust and Bevy.

Columns are numbered in the order of the terms, from 0; filters have none. The T asked for must be the component's own size, or the call throws instead of reading the memory as something else.

schedule.Add("Remove the fallen", [transform.Read(), health.Read()], [player.Without()], static context =>{    foreach (Chunk chunk in context.Chunks)    {        ReadOnlySpan<Transform> places = chunk.GetReadOnlySpan<Transform>(0);        ReadOnlySpan<Health> lives = chunk.GetReadOnlySpan<Health>(1);        ReadOnlySpan<ulong> entities = chunk.Entities;
        for (int row = 0; row < chunk.Count; row++)        {            if (lives[row].Current <= 0 || places[row].TranslationY < -50f)            {                context.Commands.Despawn(entities[row]);            }        }    }}, structural: StructuralAccess.None.AndDespawn);

A chunk points into the engine's memory only while the system runs. Chunk is a ref struct, so the compiler stops you keeping one in a field or a lambda. Anything that changes which components an entity carries while the system runs, such as world.AddComponent, world.SetLayer or world.SetActive, can move rows between tables: the chunks resolved before it are then stale, and the next span asked of them throws, saying to resolve again. Commands never do this, as they wait until the systems have run.

Resources

A generated system takes resources as Res<T> to read and ResMut<T> to write. A system written by hand declares them as resource terms, score.Read() or score.Write() on the ResourceType<T> that world.RegisterResource<T>() or world.Resource<T>() gives, and reaches them by their place in that list:

schedule.Add("Count coins", [coin.Read()], default, [score.Write()], static context =>{    ref Score total = ref context.ResourceMut<Score>(0).Value;    foreach (Chunk chunk in context.Chunks)    {        total.Coins += chunk.Count;    }});

context.Resource<T>(index) reads one. A system that declares only resources has no chunks and runs once a frame.

The order systems run in

A frame runs the fixed systems first, as many times as there are fixed steps, then the frame's systems. Within a schedule, systems run in the order they were added, one after another on the engine thread. Plugins add them in the order they are built:

  • A game's packages' plugins are built before the game's own, each package after the packages it needs.
  • Within one assembly, plugins marked [ExecuteAlways] are built first. The rest are built in no order you should rely on, so a plugin that needs another's systems before its own builds that plugin itself, with schedule.AddPlugin(new Other()), at the point in its Build where they belong.

To put one system before another regardless of when they were added, pass their ids:

SystemId input = Steering.AddRead(schedule, world.Component<Pilot>());SystemId move = Steering.AddMove(schedule, world.Transform(), world.Component<Pilot>());schedule.RunBefore(input, move);   // or schedule.RunAfter(move, input)

schedule.RunAlone(id) puts a system between the others: every system added before it runs before it, and every one added after it runs after it, whatever RunBefore says.

Orders that contradict each other, such as A before B and B before A, form a cycle. The schedule refuses it when it is built, which it does on its first run after a system was added: Build throws an InvalidOperationException naming the systems in the cycle.

What the systems record with context.Commands is applied once all of them have run, in the order they ran. So a system sees what earlier systems wrote into components in the same frame, but the entities they spawned only from the next frame.

Systems at a fixed rate

A system marked [AbyssSystem(Fixed = true)], or added to schedule.Fixed by hand, runs once for each step of the game's fixed clock, with the step as its context.DeltaTime. A frame takes as many steps as the game's time has moved on by: none, one or several. The steps run before the frame's systems, and never before the game's first frame has run.

schedule.Fixed.Add("Push", [velocity.Write(), wind.Read()], static context =>{    foreach (Chunk chunk in context.Chunks)    {        Span<Velocity> velocities = chunk.GetSpan<Velocity>(0);        ReadOnlySpan<Wind> winds = chunk.GetReadOnlySpan<Wind>(1);        for (int row = 0; row < chunk.Count; row++)        {            velocities[row].X += winds[row].Strength * context.DeltaTime;        }    }});

The fixed systems are a schedule of their own: they are ordered among themselves with schedule.Fixed.RunBefore, and never against the frame's systems. What a fixed system records is applied after its step, before the next step.

Edit ▸ Project Settings ▸ Time sets the clock, in settings/time.json:

SettingWhat it does
Fixed TimestepSeconds between two fixed steps: a sixtieth of a second unless you change it.
Maximum Allowed TimestepThe most one frame may move the game's time on. A slow frame, such as one spent loading, is followed by the steps that fit in this, not by a burst of catch-up steps.
Time ScaleHow fast the game's time runs as it starts: 1 as fast as time passes, 0 not at all.

world.Time reads the clock from any code:

MemberWhat it is
DeltaTimeSeconds of the game's time this frame: none while paused, scaled, and never more than the Maximum Allowed Timestep. Inside a fixed step, the step.
UnscaledDeltaTimeSeconds that really passed, for what goes on whatever the game's time does, such as a pause menu.
ElapsedTimeSeconds of the game's time since it started, since Play in the editor.
FixedDeltaTimeThe Fixed Timestep.
FixedOverstepHow far the clock is past its last step, from 0 to 1: how far to draw something between where the last two steps put it, so it moves smoothly at any frame rate.
InFixedStepWhether the fixed systems are running.
ScaleHow fast the game's time runs, from the next frame. Set it to 0.25 for slow motion, or 0 to stop the game's time.

Every system runs on the game's time, fixed or not: it stands still while the game is paused and follows Scale.

One system on every core

A game's systems run one after another, so one system over many entities is one loop on one thread unless it asks for more. [AbyssSystem(Parallel = true)] cuts the system's chunks into slices that several threads run at once. A system written by hand asks the same of its context:

schedule.Add("Wobble", [transform.Write(), wobble.Write()], static context =>    context.ForEachChunkParallel(static (Chunk chunk, in SystemContext slice) =>    {        Span<Transform> transforms = chunk.GetSpan<Transform>(0);        Span<Wobble> wobbles = chunk.GetSpan<Wobble>(1);        for (int i = 0; i < transforms.Length; i++)        {            ref Wobble bob = ref wobbles[i];            bob.Phase += bob.Speed * slice.DeltaTime;            transforms[i].TranslationY = bob.Height * MathF.Sin(bob.Phase);        }    }));

A slice is part of one chunk, its spans starting at its first row. There are about four slices for each of the machine's threads, never fewer than minimumSlice rows each, 1,024 unless you pass another number. The .NET thread pool and the thread that called take slices until none are left, and the call returns when all of them have run. Once warm, nothing is allocated.

A slice has its rows, DeltaTime, Frame, the resources the system reads and Selection. Everything that would be written from several threads at once is refused: Commands, Gizmos, ResourceMut, Assets, Scenes, Services, Events, Input, Localization, Text and TextOf, and any call on the world. The build refuses a parallel system that writes a resource (ABYSS016), touches no component (ABYSS017) or uses one of those in its body (ABYSS018), and the slice's context throws for what the build cannot see. Read what the loop needs before the call, and record, draw and write after it, or in a system of its own that runs next.

The result is the same as the loop on one thread as long as each row is written only from that row. Which thread runs which slice changes from frame to frame. For random numbers inside a slice, use GameRandom.Shared, which each thread has its own of, or GameRandom.Hash, which needs none (see Noise and random numbers).

Slices pay for themselves over many thousands of entities, and cost more than they save over a few hundred. Performance has the numbers.

When a system fails

A system that throws does not stop the frame. The exception is written to the Logs panel as an error under schedule, naming the system and the frame, and the other systems run as usual:

system 'Doors' threw on frame 1200: System.IndexOutOfRangeException: ...

A system that throws every frame is written in full once, then as one line every hundred frames, until it runs once without throwing:

system 'Doors' has now failed 100 frames in a row: IndexOutOfRangeException: ...

What the system recorded before it threw is applied with everything else, and what it borrowed of the world is given back, so the next frame starts clean. A command that fails as it is applied, such as one giving a mesh that does not exist, is reported as a failure of the system that recorded it. What a flow or a plugin's hook throws is reported too; see A game's start, flows and services.

Changing the world while it plays

A system cannot create or remove entities, or change which components they carry, while it runs: that would move rows between tables under the chunks it is reading. It records commands into context.Commands, its own buffer, and the schedule applies every buffer once the systems have run.

Declaring what a system may change

A system declares the changes it may record as its structural argument, separately from its query. Declaring nothing means recording nothing.

DeclarationWhat it allows
StructuralAccess.NoneNothing; the default.
StructuralAccess.Using(a, b)Spawning entities of the archetypes a and b, and giving or taking away their components.
.AndDespawnDespawn.
.AndReparentSetParent and ClearParent.
.AndInstantiateInstantiate, an instance of a prefab.
.AndSetMeshSetMesh.
.AndSetMaterialSetMaterial.
.AndSetSceneSpawning into a scene, MoveToScene and LeaveScene.
.AndAnimatePlay, Stop and SetLayerWeight on an animator.
.AndSetNameSetName, an entity's name.
StructuralAccess.EverythingAnything, for a system whose changes cannot be listed.

They combine: StructuralAccess.Using(spark).AndDespawn.AndSetMesh. Recording what was not declared throws at the call, which is the system failing, with a message saying what it declared.

Archetypes

An archetype is a set of components that entities are spawned with, given or stripped of. Make it once, in Build, from component types: Archetype spark = world.CreateArchetype(world.Transform(), world.GlobalTransform(), world.Component<Spark>());.

Spawning entities

Spawn(archetype, count) records count entities at once and returns a SpawnBatch: their ids, and a span for each component of the archetype, in the archetype's order, to write their first values into.

schedule.Add("Burst", [burst.Write()], context =>{    foreach (Chunk chunk in context.Chunks)    {        Span<Burst> bursts = chunk.GetSpan<Burst>(0);        for (int row = 0; row < chunk.Count; row++)        {            if (!bursts[row].Ready)            {                continue;            }
            bursts[row].Ready = false;            SpawnBatch sparks = context.Commands.Spawn(spark, 100);            sparks.GetSpan<Transform>(0).Fill(Transform.Identity);            Span<Spark> each = sparks.GetSpan<Spark>(2);            for (int i = 0; i < each.Length; i++)            {                each[i] = new Spark { Life = 1f + (0.01f * i) };            }        }    }}, structural: StructuralAccess.Using(spark));

A new component starts as its field initializers say, or zeroed. A zeroed Transform has no size and no rotation, so fill a batch's transforms with Transform.Identity. The spans point into the buffer and are good only until the next command recorded on it: fill them first. Spawn(archetype, count, scene) puts the new entities in a scene, and also needs .AndSetScene.

Spawned entities are data only. To draw them, give them a mesh with SetMesh; to make something the player sees from a prefab, Instantiate it, as Instance prefabs from code shows.

Giving and taking away components

AddComponents(archetype, entities) gives each of the entities the archetype's components and returns a ComponentBatch of spans for their values, one row for each entity in the order given. RemoveComponents(archetype, entity) takes them away. This is how an entity picks up a status or stops being a target:

ComponentBatch stuns = context.Commands.AddComponents(stunned, hit);stuns.GetSpan<Stun>(0).Fill(new Stun { Seconds = 2f });
context.Commands.RemoveComponents(stunned, recovered);

Giving a component an entity already has overwrites its value, and taking away one it lacks does nothing, so a system can say "make sure it is stunned" without asking first. A command buffer spawns and gives only components declared in C# and the engine's own, such as Transform; a light, or any other component of Bevy's, a plugin's or your crate's, is put on another way, as Components from Rust and Bevy shows.

Despawning

Despawn(entity), or Despawn(entities) for many in one command, removes entities. What is under an entity goes with it, so despawning the top of a prefab's instance removes all of the instance. Despawning an entity that is already gone does nothing.

When commands apply

  • Once every system of the schedule has run, buffer by buffer in the order the systems ran, and each buffer in the order its commands were recorded.
  • The ids of entities a command creates are there at once, before it applies, so the same system can record more for them: give them a parent, a mesh, more components.
  • A command that names an entity gone by the time it applies, because another system despawned it this frame, is skipped rather than an error.
  • The next frame's systems see the result.

Between frames

Code that runs between frames, such as a flow or a plugin's hook, has the world to itself. It can make a buffer of its own with world.CreateCommandBuffer(), which may record anything, and apply it with world.Apply(commands); instantiate at once with world.Instantiate; or call world.AddComponent and world.RemoveComponent, which change the entity at once. See A game's start, flows and services.

Events

A system reads what has happened from lists that are read once a frame, so every system of the frame sees the same.

Animation events are structs marked [AnimationEvent] that a clip fires as it plays past them. context.Events<T>() gives those of type T fired on the last frame, in the order they fired, each a Fired<T>:

foreach (Fired<Footstep> step in context.Events<Footstep>()){    // step.Animator, step.Clip, step.Time, step.Weight and the struct, step.Event}

A flow waits for the next one on an animator with await flow.AnimationEvent<Footstep>(animator). Events shows how they are placed on a clip, and Animation events in code how they are read.

Contacts and triggers come from the physics packages, through their services: context.Services.Get<Physics2D>() and context.Services.Get<Physics3D>() list what began touching, stayed and parted, and what entered and left triggers. See What touched in Physics 2D and Collisions in Physics 3D.

Input is read through context.Input, which says what was pressed and released this frame; see Read actions in code.

Strings in the player's language come through context.Localization; see Strings in code.

In the Scripting API