From 54d90041f9a08f42241c987cbd4d34765f0b8cfe Mon Sep 17 00:00:00 2001 From: Aevyrie Date: Tue, 19 Jul 2022 20:54:03 +0000 Subject: [PATCH] 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>`. --- ## Changelog > `send_event`, `send_default_event`, and `send_event_batch` methods added to `World`. --- crates/bevy_ecs/src/world/mod.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index fb36921bafe7da..2bbec2aaa9e857 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -1156,6 +1156,30 @@ impl World { result } + /// Sends an [`Event`](crate::event::Event). + #[inline] + pub fn send_event(&mut self, event: E) { + self.send_event_batch(std::iter::once(event)); + } + + /// Sends the default value of the [`Event`](crate::event::Event) of type `E`. + #[inline] + pub fn send_default_event(&mut self) { + self.send_event_batch(std::iter::once(E::default())); + } + + /// Sends a batch of [`Event`](crate::event::Event)s from an iterator. + #[inline] + pub fn send_event_batch(&mut self, events: impl Iterator) { + match self.get_resource_mut::>() { + Some(mut events_resource) => events_resource.extend(events), + None => bevy_utils::tracing::error!( + "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 ", + std::any::type_name::() + ), + } + } + /// # Safety /// `component_id` must be assigned to a component of type `R` #[inline]