//! In this example a system sends a custom buffered event with a 50/50 chance during any frame.1//! If an event was sent, it will be printed by the console in a receiving system.23#![expect(clippy::print_stdout, reason = "Allowed in examples.")]45use bevy_ecs::{event::EventRegistry, prelude::*};67fn main() {8// Create a new empty world and add the event as a resource9let mut world = World::new();10// The event registry is stored as a resource, and allows us to quickly update all events at once.11// This call adds both the registry resource and the events resource into the world.12EventRegistry::register_event::<MyEvent>(&mut world);1314// Create a schedule to store our systems15let mut schedule = Schedule::default();1617// Buffered events need to be updated every frame in order to clear our buffers.18// This update should happen before we use the events.19// Here, we use system sets to control the ordering.20#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]21pub struct EventFlusherSystems;2223schedule.add_systems(bevy_ecs::event::event_update_system.in_set(EventFlusherSystems));2425// Add systems sending and receiving events after the events are flushed.26schedule.add_systems((27sending_system.after(EventFlusherSystems),28receiving_system.after(sending_system),29));3031// Simulate 10 frames of our world32for iteration in 1..=10 {33println!("Simulating frame {iteration}/10");34schedule.run(&mut world);35}36}3738// This is our event that we will send and receive in systems39#[derive(BufferedEvent)]40struct MyEvent {41pub message: String,42pub random_value: f32,43}4445// In every frame we will send an event with a 50/50 chance46fn sending_system(mut event_writer: EventWriter<MyEvent>) {47let random_value: f32 = rand::random();48if random_value > 0.5 {49event_writer.write(MyEvent {50message: "A random event with value > 0.5".to_string(),51random_value,52});53}54}5556// This system listens for events of the type MyEvent57// If an event is received it will be printed to the console58fn receiving_system(mut event_reader: EventReader<MyEvent>) {59for my_event in event_reader.read() {60println!(61" Received message {}, with random value of {}",62my_event.message, my_event.random_value63);64}65}666768