system_param/
system_param.rs

1//! This example creates a custom [`SystemParam`] struct that counts the number of players.
2
3use bevy::{ecs::system::SystemParam, prelude::*};
4
5fn main() {
6    App::new()
7        .insert_resource(PlayerCount(0))
8        .add_systems(Startup, spawn)
9        .add_systems(Update, count_players)
10        .run();
11}
12
13#[derive(Component)]
14struct Player;
15
16#[derive(Resource)]
17struct PlayerCount(usize);
18
19/// The [`SystemParam`] struct can contain any types that can also be included in a
20/// system function signature.
21///
22/// In this example, it includes a query and a mutable resource.
23#[derive(SystemParam)]
24struct PlayerCounter<'w, 's> {
25    players: Query<'w, 's, &'static Player>,
26    count: ResMut<'w, PlayerCount>,
27}
28
29impl<'w, 's> PlayerCounter<'w, 's> {
30    fn count(&mut self) {
31        self.count.0 = self.players.iter().len();
32    }
33}
34
35/// Spawn some players to count
36fn spawn(mut commands: Commands) {
37    commands.spawn(Player);
38    commands.spawn(Player);
39    commands.spawn(Player);
40}
41
42/// The [`SystemParam`] can be used directly in a system argument.
43fn count_players(mut counter: PlayerCounter) {
44    counter.count();
45
46    println!("{} players in the game", counter.count.0);
47}