Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_ecs/examples/events.rs
6598 views
1
//! In this example a system sends a custom buffered event with a 50/50 chance during any frame.
2
//! If an event was sent, it will be printed by the console in a receiving system.
3
4
#![expect(clippy::print_stdout, reason = "Allowed in examples.")]
5
6
use bevy_ecs::{event::EventRegistry, prelude::*};
7
8
fn main() {
9
// Create a new empty world and add the event as a resource
10
let mut world = World::new();
11
// The event registry is stored as a resource, and allows us to quickly update all events at once.
12
// This call adds both the registry resource and the events resource into the world.
13
EventRegistry::register_event::<MyEvent>(&mut world);
14
15
// Create a schedule to store our systems
16
let mut schedule = Schedule::default();
17
18
// Buffered events need to be updated every frame in order to clear our buffers.
19
// This update should happen before we use the events.
20
// Here, we use system sets to control the ordering.
21
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
22
pub struct EventFlusherSystems;
23
24
schedule.add_systems(bevy_ecs::event::event_update_system.in_set(EventFlusherSystems));
25
26
// Add systems sending and receiving events after the events are flushed.
27
schedule.add_systems((
28
sending_system.after(EventFlusherSystems),
29
receiving_system.after(sending_system),
30
));
31
32
// Simulate 10 frames of our world
33
for iteration in 1..=10 {
34
println!("Simulating frame {iteration}/10");
35
schedule.run(&mut world);
36
}
37
}
38
39
// This is our event that we will send and receive in systems
40
#[derive(BufferedEvent)]
41
struct MyEvent {
42
pub message: String,
43
pub random_value: f32,
44
}
45
46
// In every frame we will send an event with a 50/50 chance
47
fn sending_system(mut event_writer: EventWriter<MyEvent>) {
48
let random_value: f32 = rand::random();
49
if random_value > 0.5 {
50
event_writer.write(MyEvent {
51
message: "A random event with value > 0.5".to_string(),
52
random_value,
53
});
54
}
55
}
56
57
// This system listens for events of the type MyEvent
58
// If an event is received it will be printed to the console
59
fn receiving_system(mut event_reader: EventReader<MyEvent>) {
60
for my_event in event_reader.read() {
61
println!(
62
" Received message {}, with random value of {}",
63
my_event.message, my_event.random_value
64
);
65
}
66
}
67
68