Skip to content

Commit

Permalink
Add helpers to send Events from World (#5355)
Browse files Browse the repository at this point in the history
# 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`.
  • Loading branch information
aevyrie committed Jul 19, 2022
1 parent 44e9cd4 commit 282f8ed
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions crates/bevy_ecs/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1156,6 +1156,30 @@ impl World {
result
}

/// Sends an [`Event`](crate::event::Event).
#[inline]
pub fn send_event<E: crate::event::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<E: crate::event::Event + Default>(&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<E: crate::event::Event>(&mut self, events: impl Iterator<Item = E>) {
match self.get_resource_mut::<crate::event::Events<E>>() {
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::<E>()
),
}
}

/// # Safety
/// `component_id` must be assigned to a component of type `R`
#[inline]
Expand Down

0 comments on commit 282f8ed

Please sign in to comment.