| 1 |
|
| 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 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 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 |
|
| 36 |
fn spawn(mut commands: Commands) { |
| 37 |
commands.spawn(Player); |
| 38 |
commands.spawn(Player); |
| 39 |
commands.spawn(Player); |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
fn count_players(mut counter: PlayerCounter) { |
| 44 |
counter.count(); |
| 45 |
|
| 46 |
println!("{} players in the game", counter.count.0); |
| 47 |
} |