Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/ecs/system_param.rs
6592 views
1
//! This example creates a custom [`SystemParam`] struct that counts the number of players.
2
3
use bevy::{ecs::system::SystemParam, prelude::*};
4
5
fn 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)]
14
struct Player;
15
16
#[derive(Resource)]
17
struct 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)]
24
struct PlayerCounter<'w, 's> {
25
players: Query<'w, 's, &'static Player>,
26
count: ResMut<'w, PlayerCount>,
27
}
28
29
impl<'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
36
fn 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.
43
fn count_players(mut counter: PlayerCounter) {
44
counter.count();
45
46
println!("{} players in the game", counter.count.0);
47
}
48
49