mirror of
https://github.com/bevyengine/bevy
synced 2024-11-22 12:43:34 +00:00
81b53d15d4
Resolves #1253 #1562 This makes the Commands apis consistent with World apis. This moves to a "type state" pattern (like World) where the "current entity" is stored in an `EntityCommands` builder. In general this tends to cuts down on indentation and line count. It comes at the cost of needing to type `commands` more and adding more semicolons to terminate expressions. I also added `spawn_bundle` to Commands because this is a common enough operation that I think its worth providing a shorthand.
51 lines
1.5 KiB
Rust
51 lines
1.5 KiB
Rust
use bevy::prelude::*;
|
|
use rand::Rng;
|
|
|
|
// This example illustrates how to react to component change
|
|
fn main() {
|
|
App::build()
|
|
.add_plugins(DefaultPlugins)
|
|
.add_startup_system(setup.system())
|
|
.add_system(change_component.system())
|
|
.add_system(change_detection.system())
|
|
.add_system(tracker_monitoring.system())
|
|
.run();
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
struct MyComponent(f64);
|
|
|
|
fn setup(mut commands: Commands) {
|
|
commands.spawn().insert(MyComponent(0.));
|
|
commands.spawn().insert(Transform::identity());
|
|
}
|
|
|
|
fn change_component(time: Res<Time>, mut query: Query<(Entity, &mut MyComponent)>) {
|
|
for (entity, mut component) in query.iter_mut() {
|
|
if rand::thread_rng().gen_bool(0.1) {
|
|
info!("changing component {:?}", entity);
|
|
component.0 = time.seconds_since_startup();
|
|
}
|
|
}
|
|
}
|
|
|
|
// There are query filters for `Changed<T>` and `Added<T>`
|
|
// Only entities matching the filters will be in the query
|
|
fn change_detection(query: Query<(Entity, &MyComponent), Changed<MyComponent>>) {
|
|
for (entity, component) in query.iter() {
|
|
info!("{:?} changed: {:?}", entity, component,);
|
|
}
|
|
}
|
|
|
|
// By looking at trackers, the query is not filtered but the information is available
|
|
fn tracker_monitoring(
|
|
query: Query<(
|
|
Entity,
|
|
Option<&MyComponent>,
|
|
Option<ChangeTrackers<MyComponent>>,
|
|
)>,
|
|
) {
|
|
for (entity, component, trackers) in query.iter() {
|
|
info!("{:?}: {:?} -> {:?}", entity, component, trackers);
|
|
}
|
|
}
|