Open-Source Wikis

/

Bevy

/

Primitives

/

Query

bevyengine/bevy

Query

A Query<D, F> is a system parameter that iterates entities matching a component signature. D is the data the query fetches; F is the optional filter.

The basic shape

use bevy::prelude::*;

fn move_things(
    mut q: Query<(&mut Transform, &Velocity)>,
) {
    for (mut t, v) in &mut q {
        t.translation += v.0 * 0.016;
    }
}

The signature (&mut Transform, &Velocity) says "entities with a Transform (mutable) and a Velocity (read-only)." Iteration only visits matching entities.

Filters

Query<&Transform, With<Player>>          // has Transform AND Player (don't fetch Player)
Query<&Transform, Without<Camera>>       // has Transform but NOT Camera
Query<&Transform, Or<(With<A>, With<B>)>>  // has Transform and (A or B)
Query<&Transform, Changed<Transform>>    // has Transform that changed this tick
Query<&Transform, Added<Transform>>      // has Transform that was just added

Filters compose: (With<A>, Without<B>) means "has A and not B."

Single-entity queries

fn check_player(q: Query<&Transform, With<Player>>) {
    let player_transform = q.single();   // panics if 0 or >1 matches
    // or:
    let Ok(t) = q.get_single() else { return };
}

When you expect exactly one match, single/get_single is cleaner than iterating.

Direct lookup

fn check(q: Query<&Health>, target: Entity) {
    if let Ok(h) = q.get(target) {
        // …
    }
}

Query::get returns Result for a specific entity.

Mutability and parallelism

Query<&mut T> requires exclusive access to T's archetypes. Two systems with Query<&mut T> for the same T cannot run in parallel. The schedule executor enforces this — it's the central invariant that lets parallelism be transparent.

Query<&T> is shareable; many systems can read the same component concurrently.

Iterating in parallel

For large queries:

q.par_iter_mut().for_each(|(mut t, v)| {
    t.translation += v.0 * 0.016;
});

par_iter and par_iter_mut use bevy_tasks to split iteration across threads. The split granularity comes from the archetype layout, which keeps each chunk cache-friendly.

QueryState

A QueryState is the cached lookup behind a Query. Most users never touch it. If you need to query inside an exclusive system (&mut World):

fn extra(world: &mut World) {
    let mut state = world.query::<&Health>();
    for h in state.iter(&world) { /* ... */ }
}

See also

  • System — queries are system parameters.
  • Component — what queries iterate.
  • bevy_ecscrates/bevy_ecs/src/query/.

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

Query – Bevy wiki | Factory