Path: blob/main/crates/bevy_ecs/examples/change_detection.rs
6598 views
//! In this example we will simulate a population of entities. In every tick we will:1//! 1. spawn a new entity with a certain possibility2//! 2. age all entities3//! 3. despawn entities with age > 24//!5//! To demonstrate change detection, there are some console outputs based on changes in6//! the `EntityCounter` resource and updated Age components78#![expect(9clippy::std_instead_of_core,10clippy::print_stdout,11reason = "Examples should not follow this lint"12)]1314use bevy_ecs::prelude::*;15use rand::Rng;16use std::ops::Deref;1718fn main() {19// Create a new empty World to hold our Entities, Components and Resources20let mut world = World::new();2122// Add the counter resource to remember how many entities where spawned23world.insert_resource(EntityCounter { value: 0 });2425// Create a new Schedule, which stores systems and controls their relative ordering26let mut schedule = Schedule::default();2728// Add systems to the Schedule to execute our app logic29// We can label our systems to force a specific run-order between some of them30schedule.add_systems((31spawn_entities.in_set(SimulationSystems::Spawn),32print_counter_when_changed.after(SimulationSystems::Spawn),33age_all_entities.in_set(SimulationSystems::Age),34remove_old_entities.after(SimulationSystems::Age),35print_changed_entities.after(SimulationSystems::Age),36));3738// Simulate 10 frames in our world39for iteration in 1..=10 {40println!("Simulating frame {iteration}/10");41schedule.run(&mut world);42}43}4445// This struct will be used as a Resource keeping track of the total amount of spawned entities46#[derive(Debug, Resource)]47struct EntityCounter {48pub value: i32,49}5051// This struct represents a Component and holds the age in frames of the entity it gets assigned to52#[derive(Component, Default, Debug)]53struct Age {54frames: i32,55}5657// System sets can be used to group systems and configured to control relative ordering58#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]59enum SimulationSystems {60Spawn,61Age,62}6364// This system randomly spawns a new entity in 60% of all frames65// The entity will start with an age of 0 frames66// If an entity gets spawned, we increase the counter in the EntityCounter resource67fn spawn_entities(mut commands: Commands, mut entity_counter: ResMut<EntityCounter>) {68if rand::rng().random_bool(0.6) {69let entity_id = commands.spawn(Age::default()).id();70println!(" spawning {entity_id:?}");71entity_counter.value += 1;72}73}7475// This system prints out changes in our entity collection76// For every entity that just got the Age component added we will print that it's the77// entities first birthday. These entities where spawned in the previous frame.78// For every entity with a changed Age component we will print the new value.79// In this example the Age component is changed in every frame, so we don't actually80// need the `Changed` here, but it is still used for the purpose of demonstration.81fn print_changed_entities(82entity_with_added_component: Query<Entity, Added<Age>>,83entity_with_mutated_component: Query<(Entity, &Age), Changed<Age>>,84) {85for entity in &entity_with_added_component {86println!(" {entity} has its first birthday!");87}88for (entity, value) in &entity_with_mutated_component {89println!(" {entity} is now {value:?} frames old");90}91}9293// This system iterates over all entities and increases their age in every frame94fn age_all_entities(mut entities: Query<&mut Age>) {95for mut age in &mut entities {96age.frames += 1;97}98}99100// This system iterates over all entities in every frame and despawns entities older than 2 frames101fn remove_old_entities(mut commands: Commands, entities: Query<(Entity, &Age)>) {102for (entity, age) in &entities {103if age.frames > 2 {104println!(" despawning {entity} due to age > 2");105commands.entity(entity).despawn();106}107}108}109110// This system will print the new counter value every time it was changed since111// the last execution of the system.112fn print_counter_when_changed(entity_counter: Res<EntityCounter>) {113if entity_counter.is_changed() {114println!(115" total number of entities spawned: {}",116entity_counter.deref().value117);118}119}120121122