mirror of
https://github.com/bevyengine/bevy
synced 2024-11-30 08:30:24 +00:00
07ed1d053e
This implements the most minimal variant of #1843 - a derive for marker trait. This is a prerequisite to more complicated features like statically defined storage type or opt-out component reflection. In order to make component struct's purpose explicit and avoid misuse, it must be annotated with `#[derive(Component)]` (manual impl is discouraged for compatibility). Right now this is just a marker trait, but in the future it might be expanded. Making this change early allows us to make further changes later without breaking backward compatibility for derive macro users. This already prevents a lot of issues, like using bundles in `insert` calls. Primitive types are no longer valid components as well. This can be easily worked around by adding newtype wrappers and deriving `Component` for them. One funny example of prevented bad code (from our own tests) is when an newtype struct or enum variant is used. Previously, it was possible to write `insert(Newtype)` instead of `insert(Newtype(value))`. That code compiled, because function pointers (in this case newtype struct constructor) implement `Send + Sync + 'static`, so we allowed them to be used as components. This is no longer the case and such invalid code will trigger a compile error. Co-authored-by: = <=> Co-authored-by: TheRawMeatball <therawmeatball@gmail.com> Co-authored-by: Carter Anderson <mcanders1@gmail.com>
45 lines
1.2 KiB
Rust
45 lines
1.2 KiB
Rust
use bevy::{ecs::system::SystemParam, prelude::*};
|
|
|
|
/// This example creates a SystemParam struct that counts the number of players
|
|
fn main() {
|
|
App::new()
|
|
.insert_resource(PlayerCount(0))
|
|
.add_startup_system(spawn)
|
|
.add_system(count_players)
|
|
.run();
|
|
}
|
|
|
|
#[derive(Component)]
|
|
pub struct Player;
|
|
#[derive(Component)]
|
|
pub 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)]
|
|
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();
|
|
}
|
|
}
|
|
|
|
/// Spawn some players to count
|
|
fn spawn(mut commands: Commands) {
|
|
commands.spawn().insert(Player);
|
|
commands.spawn().insert(Player);
|
|
commands.spawn().insert(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);
|
|
}
|