Skip to content

Commit 282f8ed

Browse files
committed
Add helpers to send Events from World (#5355)
# Objective - With access to `World`, it's not obvious how to send an event. - This is especially useful if you are writing a `Command` that needs to send an `Event`. - `Events` are a first-class construct in bevy, even though they are just `Resources` under the hood. Their methods should be discoverable. ## Solution - Provide a simple helpers to send events through `Res<Events<T>>`. --- ## Changelog > `send_event`, `send_default_event`, and `send_event_batch` methods added to `World`.
1 parent 44e9cd4 commit 282f8ed

File tree

1 file changed

+24
-0
lines changed
  • crates/bevy_ecs/src/world

1 file changed

+24
-0
lines changed

crates/bevy_ecs/src/world/mod.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1156,6 +1156,30 @@ impl World {
11561156
result
11571157
}
11581158

1159+
/// Sends an [`Event`](crate::event::Event).
1160+
#[inline]
1161+
pub fn send_event<E: crate::event::Event>(&mut self, event: E) {
1162+
self.send_event_batch(std::iter::once(event));
1163+
}
1164+
1165+
/// Sends the default value of the [`Event`](crate::event::Event) of type `E`.
1166+
#[inline]
1167+
pub fn send_default_event<E: crate::event::Event + Default>(&mut self) {
1168+
self.send_event_batch(std::iter::once(E::default()));
1169+
}
1170+
1171+
/// Sends a batch of [`Event`](crate::event::Event)s from an iterator.
1172+
#[inline]
1173+
pub fn send_event_batch<E: crate::event::Event>(&mut self, events: impl Iterator<Item = E>) {
1174+
match self.get_resource_mut::<crate::event::Events<E>>() {
1175+
Some(mut events_resource) => events_resource.extend(events),
1176+
None => bevy_utils::tracing::error!(
1177+
"Unable to send event `{}`\n\tEvent must be added to the app with `add_event()`\n\thttps://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event ",
1178+
std::any::type_name::<E>()
1179+
),
1180+
}
1181+
}
1182+
11591183
/// # Safety
11601184
/// `component_id` must be assigned to a component of type `R`
11611185
#[inline]

0 commit comments

Comments
 (0)