|
| 1 | +use bevy::core::FixedTimestep; |
| 2 | +use bevy::prelude::*; |
| 3 | + |
| 4 | +/// Events are automatically cleaned up after two frames when intialized via `.add_event`. |
| 5 | +/// To bypass this, you can simply add the Events::<T> resource manually. |
| 6 | +/// This is critical when working with systems that read events but do not run every tick, |
| 7 | +/// such as those that operate with a FixedTimeStep run criteria. |
| 8 | +/// |
| 9 | +/// When you do so though, you need to be careful to clean up these events eventually, |
| 10 | +/// otherwise the size of your vector of events will grow in an unbounded fashion. |
| 11 | +/// |
| 12 | +/// `EventConsumer::<T>` provides a simple interface to do so, clearing all events that it reads |
| 13 | +/// by draining them into a new vector. |
| 14 | +/// You can combine it with other `EventReader`s as long as they read events before , |
| 15 | +/// but only one `EventConsumer` system should be used per event type in most cases |
| 16 | +/// as they will compete for events. |
| 17 | +fn main() { |
| 18 | + App::build() |
| 19 | + .add_plugins(DefaultPlugins) |
| 20 | + .add_event::<MyEvent>() |
| 21 | + .add_system( |
| 22 | + event_trigger_system |
| 23 | + .system() |
| 24 | + .with_run_criteria(FixedTimestep::step(1.0)), |
| 25 | + ) |
| 26 | + .add_system(event_listener_system.system().label("listening")) |
| 27 | + .add_system( |
| 28 | + event_devourer_system |
| 29 | + .system() |
| 30 | + // Must occur after event_listener_system or some events may be missed |
| 31 | + .after("listening") |
| 32 | + .with_run_criteria(FixedTimestep::step(5.0)), |
| 33 | + ) |
| 34 | + .run(); |
| 35 | +} |
| 36 | + |
| 37 | +struct MyEvent { |
| 38 | + pub message: String, |
| 39 | +} |
| 40 | + |
| 41 | +// sends MyEvent every second |
| 42 | +fn event_trigger_system(time: Res<Time>, mut my_events: EventWriter<MyEvent>) { |
| 43 | + my_events.send(MyEvent { |
| 44 | + message: format!( |
| 45 | + "This event was sent at {}", |
| 46 | + time.time_since_startup().as_millis() |
| 47 | + ) |
| 48 | + .to_string(), |
| 49 | + }); |
| 50 | +} |
| 51 | + |
| 52 | +// reads events as soon as they come in |
| 53 | +fn event_listener_system(mut events: EventReader<MyEvent>) { |
| 54 | + for _ in events.iter() { |
| 55 | + info!("I heard an event!"); |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +// reports events once every 5 seconds |
| 60 | +fn event_devourer_system(events: EventConsumer<MyEvent>) { |
| 61 | + // Events are only consumed when .drain() is called |
| 62 | + for my_event in events.drain() { |
| 63 | + info!("{}", my_event.message); |
| 64 | + } |
| 65 | +} |
0 commit comments