bevy/examples/ecs/system_param.rs
Wouter Buckens 000dd4c1c2 Add docs & example for SystemParam (#1435)
It took me a little while to figure out how to use the `SystemParam` derive macro to easily create my own params. So I figured I'd add some docs and an example with what I learned.

- Fixed a bug in the `SystemParam` derive macro where it didn't detect the correct crate name when used in an example (no longer relevant, replaced by #1426 - see further)
- Added some doc comments and a short example code block in the docs for the `SystemParam` trait
- Added a more complete example with explanatory comments in examples
2021-03-03 03:11:11 +00:00

44 lines
1.1 KiB
Rust

use bevy::{ecs::SystemParam, prelude::*};
/// This example creates a SystemParam struct that counts the number of players
fn main() {
App::build()
.insert_resource(PlayerCount(0))
.add_startup_system(spawn.system())
.add_system(count_players.system())
.run();
}
struct Player;
struct PlayerCount(usize);
/// The SystemParam struct can contain any types that can also be included in a
/// system function signature.
///
/// In this example, it includes a query and a mutable resource.
#[derive(SystemParam)]
pub struct PlayerCounter<'a> {
players: Query<'a, &'a Player>,
count: ResMut<'a, PlayerCount>,
}
impl<'a> PlayerCounter<'a> {
fn count(&mut self) {
self.count.0 = self.players.iter().len();
}
}
/// Spawn some players to count
fn spawn(commands: &mut Commands) {
commands.spawn((Player,));
commands.spawn((Player,));
commands.spawn((Player,));
}
/// 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);
}