callbacks/callbacks.rs
1//! Sometimes, you want an extremely flexible way to store logic associated with an entity.
2//! This example demonstrates how to store arbitrary systems in components and run them on demand.
3//!
4//! This pattern trades some performance for flexibility and works well for things like cutscenes, scripted events,
5//! or one-off UI-driven interactions that don't need to run every frame.
6
7use bevy::{ecs::system::SystemId, prelude::*};
8
9fn main() {
10 let mut app = App::new();
11 app.add_systems(Startup, setup_callbacks);
12 app.add_systems(Update, run_callbacks);
13 app.run();
14}
15
16#[derive(Component)]
17struct Callback {
18 system_id: SystemId<(), ()>,
19}
20
21fn setup_callbacks(mut commands: Commands) {
22 let trivial_callback = Callback {
23 system_id: commands.register_system(|| {
24 println!("This is the trivial callback system");
25 }),
26 };
27
28 let ordinary_system_callback = Callback {
29 system_id: commands.register_system(|query: Query<&Callback>| {
30 let n_callbacks = query.iter().len();
31 println!("This is the ordinary callback system. There are currently {n_callbacks} callbacks in the world.");
32 }),
33 };
34
35 let exclusive_callback = Callback {
36 system_id: commands.register_system(|world: &mut World| {
37 let n_entities = world.entities().len();
38 println!("This is the exclusive callback system. There are currently {n_entities} entities in the world.");
39 }),
40 };
41
42 commands.spawn(trivial_callback);
43 commands.spawn(ordinary_system_callback);
44 commands.spawn(exclusive_callback);
45}
46
47// In many cases, you might want to use an observer to detect when a callback should run,
48// triggering the callback in response to some entity-event!
49fn run_callbacks(mut commands: Commands, query: Query<&Callback>) {
50 for callback in query.iter() {
51 commands.run_system(callback.system_id);
52 }
53}