Systems
Write systems as plain functions, add them to an app's schedules, use closures, and understand how the engine runs them in parallel.
On this page
A system is the logic of your game: a plain Rust function that the engine runs, usually once per frame. Its parameters say what it needs, such as a query over components, a resource or commands. The engine fetches them for you and, because it knows what each system reads and writes, runs systems that don't conflict at the same time on different threads.
Write a system and add it#
use neo::prelude::*;
#[derive(Component)]
struct Spin(f32);
fn spin(time: Res<Time>, mut query: Query<(&mut Transform, &Spin)>) {
for (mut transform, spin) in &mut query {
transform.rotate_y(spin.0 * time.delta_secs());
}
}
fn setup(mut commands: Commands) {
commands.spawn((Transform::default(), Spin(1.0)));
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup) // once, when the app starts
.add_systems(Update, spin) // every frame
.run();
}add_systems takes a schedule and one system or a tuple of them. Startup runs once before the first frame; Update runs every frame; FixedUpdate runs at a fixed rate for gameplay and physics.
app.add_systems(Update, (move_player, move_enemies, update_score));System parameters#
Any parameter that implements SystemParam can appear in a system's signature, in any order.
| Parameter | What it gives you |
|---|---|
Query<D, F> | The entities that match a set of components. See Queries. |
Single<D, F> | Exactly one matching entity; the system is skipped otherwise. |
Populated<D, F> | A query that has at least one match; the system is skipped otherwise. |
Res<T>, ResMut<T> | A resource, read-only or mutable. See Resources. |
Option<Res<T>> | A resource that may not exist. |
Commands | Queued changes to the world. See Commands. |
MessageWriter<M>, MessageReader<M> | Write and read buffered messages. See Messages. |
Local<T> | A value owned by this system that persists between runs. |
RemovedComponents<T> | Entities that lost a T recently. |
ParamSet<(..)> | Parameters that would otherwise conflict, used one at a time. |
&World, &mut World | The whole world (&mut World makes it an exclusive system). |
A system can take up to 16 parameters; group more into a tuple or a custom parameter. Local, ParamSet, custom parameters and exclusive systems are covered in System parameters.
How systems run in parallel#
Within a schedule, systems run in parallel unless their data access conflicts:
- Two systems that only read the same data (
&Transform,Res<Time>) can run together. - A system that writes data (
&mut Transform,ResMut<Score>) can't run at the same time as another system that reads or writes it. - An exclusive system (
&mut World) runs alone.
Without explicit ordering, systems that conflict still run one after another, but in no fixed order, which can change between runs. When order matters, say so with .before, .after or .chain(). See System ordering and sets.
app.add_systems(Update, (read_input, apply_movement, check_collisions).chain());Closures as systems#
A closure works as a system too, which is handy for small one-off logic:
app.add_systems(Update, || info!("tick"));
app.add_systems(Update, |query: Query<&Name>| {
for name in &query {
info!("{name}");
}
});Systems that return values#
A system can return a value. A system returning Result is a fallible system; its errors go to the app's error handler (see Error handling). You can also pass one system's output to another with pipe, or transform it with map:
fn parse_level(name: Res<LevelName>) -> Result<u32, std::num::ParseIntError> {
name.0.parse()
}
fn report(In(result): In<Result<u32, std::num::ParseIntError>>) {
match result {
Ok(n) => info!("level {n}"),
Err(e) => warn!("bad level name: {e}"),
}
}
app.add_systems(Update, parse_level.pipe(report));
#[derive(Resource)]
struct LevelName(String);A piped pair runs as one system: the second gets the first's output through its In<T> parameter.
Generic systems#
Systems can be generic, so one function serves several component types:
fn despawn_all<T: Component>(mut commands: Commands, query: Query<Entity, With<T>>) {
for entity in &query {
commands.entity(entity).despawn();
}
}
#[derive(Component)]
struct Bullet;
#[derive(Component)]
struct Spark;
app.add_systems(Last, (despawn_all::<Bullet>, despawn_all::<Spark>));Examples#
Run these from the engine core's workspace:
| Example | What it shows |
|---|---|
cargo run --example ecs_guide | A guided tour of components, resources, systems and ordering in one program. |
cargo run --example startup_system | A startup system that runs before the first update. |
cargo run --example system_closure | Closures as systems, with captured values. |
cargo run --example system_piping | pipe and map. |
cargo run --example generic_system | One generic system used for several types. |
cargo run --example parallel_query | Iterating a query on several threads. |