Tainted\\Coders

Custom System Params

Bevy version: 0.14Last updated:

We can reduce the argument counts and control access to our queries by making custom SystemParam.

A system param is valid as long as each field of its struct is also a SystemParam like a Query, Resource, etc.

Its easy to do this using the #[derive(SystemParam)]

#[derive(SystemParam)]
struct PlayerCounter<'w, 's> {
  players: Query<'w, 's, &'static Player>,
  count: ResMut<'w, PlayerCount>,
}

impl<'w, 's> PlayerCounter<'w, 's> {
  fn count(&mut self) {
    self.count.0 = self.players.iter().len();
  }
}

// The [`SystemParam`] can be used directly in a system argument.
fn count_players(mut counter: PlayerCounter) {
  counter.count();

  println!("{} players in the game", counter.count.0);
}