Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_ecs/examples/events.rs
6849 views
1
//! In this example a system sends a custom messages with a 50/50 chance during any frame.
2
//! If a message 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::{message::MessageRegistry, prelude::*};
7
8
fn main() {
9
// Create a new empty world.
10
let mut world = World::new();
11
// The message registry is stored as a resource, and allows us to quickly update all messages at once.
12
// This call adds both the registry resource and the `Messages` resource into the world.
13
MessageRegistry::register_message::<MyMessage>(&mut world);
14
15
// Create a schedule to store our systems
16
let mut schedule = Schedule::default();
17
18
// Messages need to be updated every frame in order to clear our buffers.
19
// This update should happen before we use the messages.
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::message::message_update_system.in_set(EventFlusherSystems));
25
26
// Add systems sending and receiving messages after the messages 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 message that we will send and receive in systems
40
#[derive(Message)]
41
struct MyMessage {
42
pub message: String,
43
pub random_value: f32,
44
}
45
46
// In every frame we will send a message with a 50/50 chance
47
fn sending_system(mut message_writer: MessageWriter<MyMessage>) {
48
let random_value: f32 = rand::random();
49
if random_value > 0.5 {
50
message_writer.write(MyMessage {
51
message: "A random message with value > 0.5".to_string(),
52
random_value,
53
});
54
}
55
}
56
57
// This system listens for messages of the type MyEvent
58
// If a message is received it will be printed to the console
59
fn receiving_system(mut message_reader: MessageReader<MyMessage>) {
60
for my_message in message_reader.read() {
61
println!(
62
" Received message {}, with random value of {}",
63
my_message.message, my_message.random_value
64
);
65
}
66
}
67
68