Tainted\\Coders

Custom Queries

Bevy version: 0.19Last updated:

We can derive from QueryData to create our own custom queries that give a number of benefits:

So instead of using long winded tuple queries with many parameters like:

#[derive(Component, Debug)]
struct Health(f32);

#[derive(Component, Debug)]
struct Ammo(f32);

#[derive(Component, Debug)]
struct Player;

fn print_player_status_manually(query: Query<(&Health, &Ammo, &Player)>) {
  for (health, ammo, player) in &query {
    println!(
      "Player {:?} has {:?} health and {:?} ammo",
      player, health, ammo
    );
  }
}

We can create our own custom queries:

#[derive(QueryData)]
#[query_data(derive(Debug))]
struct PlayerQuery {
  entity: Entity,
  health: &'static Health,
  ammo: &'static Ammo,
  player: &'static Player,
}

fn print_player_status(query: Query<PlayerQuery>) {
  for player in &query {
    println!(
      "Player {:?} has {:?} health and {:?} ammo",
      player.entity, player.health, player.ammo
    );
  }
}