Struct bevy::ecs::prelude::EventWriter
source · pub struct EventWriter<'w, E>where
E: Event,{ /* private fields */ }
Expand description
Sends events of type T
.
§Usage
EventWriter
s are usually declared as a SystemParam
.
#[derive(Event)]
pub struct MyEvent; // Custom event type.
fn my_system(mut writer: EventWriter<MyEvent>) {
writer.send(MyEvent);
}
§Concurrency
EventWriter
param has ResMut<Events<T>>
inside. So two systems declaring EventWriter<T>
params
for the same event type won’t be executed concurrently.
§Untyped events
EventWriter
can only send events of one specific type, which must be known at compile-time.
This is not a problem most of the time, but you may find a situation where you cannot know
ahead of time every kind of event you’ll need to send. In this case, you can use the “type-erased event” pattern.
fn send_untyped(mut commands: Commands) {
// Send an event of a specific type without having to declare that
// type as a SystemParam.
//
// Effectively, we're just moving the type parameter from the /type/ to the /method/,
// which allows one to do all kinds of clever things with type erasure, such as sending
// custom events to unknown 3rd party plugins (modding API).
//
// NOTE: the event won't actually be sent until commands get applied during
// apply_deferred.
commands.add(|w: &mut World| {
w.send_event(MyEvent);
});
}
Note that this is considered non-idiomatic, and should only be used when EventWriter
will not work.
Implementations§
source§impl<'w, E> EventWriter<'w, E>where
E: Event,
impl<'w, E> EventWriter<'w, E>where
E: Event,
sourcepub fn send(&mut self, event: E) -> EventId<E>
pub fn send(&mut self, event: E) -> EventId<E>
Sends an event
, which can later be read by EventReader
s.
This method returns the ID of the sent event
.
See Events
for details.
Examples found in repository?
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
fn read_and_write_different_event_types(mut a: EventWriter<A>, mut b: EventReader<B>) {
for _ in b.read() {}
a.send(A);
}
/// A dummy event type.
#[derive(Debug, Clone, Event)]
struct DebugEvent {
resend_from_param_set: bool,
resend_from_local_event_reader: bool,
times_sent: u8,
}
/// A system that sends all combinations of events.
fn send_events(mut events: EventWriter<DebugEvent>, frame_count: Res<FrameCount>) {
println!("Sending events for frame {:?}", frame_count.0);
events.send(DebugEvent {
resend_from_param_set: false,
resend_from_local_event_reader: false,
times_sent: 1,
});
events.send(DebugEvent {
resend_from_param_set: true,
resend_from_local_event_reader: false,
times_sent: 1,
});
events.send(DebugEvent {
resend_from_param_set: false,
resend_from_local_event_reader: true,
times_sent: 1,
});
events.send(DebugEvent {
resend_from_param_set: true,
resend_from_local_event_reader: true,
times_sent: 1,
});
}
/// A system that prints all events sent since the last time this system ran.
///
/// Note that some events will be printed twice, because they were sent twice.
fn debug_events(mut events: EventReader<DebugEvent>) {
for event in events.read() {
println!("{:?}", event);
}
}
/// A system that both sends and receives events using [`ParamSet`].
fn send_and_receive_param_set(
mut param_set: ParamSet<(EventReader<DebugEvent>, EventWriter<DebugEvent>)>,
frame_count: Res<FrameCount>,
) {
println!(
"Sending and receiving events for frame {} with a `ParamSet`",
frame_count.0
);
// We must collect the events to resend, because we can't access the writer while we're iterating over the reader.
let mut events_to_resend = Vec::new();
// This is p0, as the first parameter in the `ParamSet` is the reader.
for event in param_set.p0().read() {
if event.resend_from_param_set {
events_to_resend.push(event.clone());
}
}
// This is p1, as the second parameter in the `ParamSet` is the writer.
for mut event in events_to_resend {
event.times_sent += 1;
param_set.p1().send(event);
}
}
More examples
38 39 40 41 42 43 44 45 46 47 48 49 50
fn event_trigger(
time: Res<Time>,
mut state: ResMut<EventTriggerState>,
mut my_events: EventWriter<MyEvent>,
mut play_sound_events: EventWriter<PlaySound>,
) {
if state.event_timer.tick(time.delta()).finished() {
my_events.send(MyEvent {
message: "MyEvent just happened!".to_string(),
});
play_sound_events.send_default();
}
}
126 127 128 129 130 131 132 133 134 135 136 137 138
fn game_over_system(
game_rules: Res<GameRules>,
game_state: Res<GameState>,
mut app_exit_events: EventWriter<AppExit>,
) {
if let Some(ref player) = game_state.winning_player {
println!("{player} won the game!");
app_exit_events.send(AppExit);
} else if game_state.current_round == game_rules.max_rounds {
println!("Ran out of rounds. Nobody wins!");
app_exit_events.send(AppExit);
}
}
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
fn keyboard_input_system(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut frequency: ResMut<PitchFrequency>,
mut events: EventWriter<PlayPitch>,
) {
if keyboard_input.just_pressed(KeyCode::ArrowUp) {
frequency.0 *= 2.0f32.powf(1.0 / 12.0);
}
if keyboard_input.just_pressed(KeyCode::ArrowDown) {
frequency.0 /= 2.0f32.powf(1.0 / 12.0);
}
if keyboard_input.just_pressed(KeyCode::Space) {
events.send(PlayPitch);
}
}
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
fn menu_action(
interaction_query: Query<
(&Interaction, &MenuButtonAction),
(Changed<Interaction>, With<Button>),
>,
mut app_exit_events: EventWriter<AppExit>,
mut menu_state: ResMut<NextState<MenuState>>,
mut game_state: ResMut<NextState<GameState>>,
) {
for (interaction, menu_button_action) in &interaction_query {
if *interaction == Interaction::Pressed {
match menu_button_action {
MenuButtonAction::Quit => {
app_exit_events.send(AppExit);
}
MenuButtonAction::Play => {
game_state.set(GameState::Game);
menu_state.set(MenuState::Disabled);
}
MenuButtonAction::Settings => menu_state.set(MenuState::Settings),
MenuButtonAction::SettingsDisplay => {
menu_state.set(MenuState::SettingsDisplay);
}
MenuButtonAction::SettingsSound => {
menu_state.set(MenuState::SettingsSound);
}
MenuButtonAction::BackToMainMenu => menu_state.set(MenuState::Main),
MenuButtonAction::BackToSettings => {
menu_state.set(MenuState::Settings);
}
}
}
}
}
sourcepub fn send_batch(
&mut self,
events: impl IntoIterator<Item = E>
) -> SendBatchIds<E> ⓘ
pub fn send_batch( &mut self, events: impl IntoIterator<Item = E> ) -> SendBatchIds<E> ⓘ
Sends a list of events
all at once, which can later be read by EventReader
s.
This is more efficient than sending each event individually.
This method returns the IDs of the sent events
.
See Events
for details.
sourcepub fn send_default(&mut self) -> EventId<E>where
E: Default,
pub fn send_default(&mut self) -> EventId<E>where
E: Default,
Sends the default value of the event. Useful when the event is an empty struct.
This method returns the ID of the sent event
.
See Events
for details.
Examples found in repository?
38 39 40 41 42 43 44 45 46 47 48 49 50
fn event_trigger(
time: Res<Time>,
mut state: ResMut<EventTriggerState>,
mut my_events: EventWriter<MyEvent>,
mut play_sound_events: EventWriter<PlaySound>,
) {
if state.event_timer.tick(time.delta()).finished() {
my_events.send(MyEvent {
message: "MyEvent just happened!".to_string(),
});
play_sound_events.send_default();
}
}
More examples
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
fn check_for_collisions(
mut commands: Commands,
mut scoreboard: ResMut<Scoreboard>,
mut ball_query: Query<(&mut Velocity, &Transform), With<Ball>>,
collider_query: Query<(Entity, &Transform, Option<&Brick>), With<Collider>>,
mut collision_events: EventWriter<CollisionEvent>,
) {
let (mut ball_velocity, ball_transform) = ball_query.single_mut();
// check collision with walls
for (collider_entity, transform, maybe_brick) in &collider_query {
let collision = collide_with_side(
BoundingCircle::new(ball_transform.translation.truncate(), BALL_DIAMETER / 2.),
Aabb2d::new(
transform.translation.truncate(),
transform.scale.truncate() / 2.,
),
);
if let Some(collision) = collision {
// Sends a collision event so that other systems can react to the collision
collision_events.send_default();
// Bricks should be despawned and increment the scoreboard on collision
if maybe_brick.is_some() {
scoreboard.score += 1;
commands.entity(collider_entity).despawn();
}
// reflect the ball when it collides
let mut reflect_x = false;
let mut reflect_y = false;
// only reflect if the ball's velocity is going in the opposite direction of the
// collision
match collision {
Collision::Left => reflect_x = ball_velocity.x > 0.0,
Collision::Right => reflect_x = ball_velocity.x < 0.0,
Collision::Top => reflect_y = ball_velocity.y < 0.0,
Collision::Bottom => reflect_y = ball_velocity.y > 0.0,
}
// reflect velocity on the x-axis if we hit something on the x-axis
if reflect_x {
ball_velocity.x = -ball_velocity.x;
}
// reflect velocity on the y-axis if we hit something on the y-axis
if reflect_y {
ball_velocity.y = -ball_velocity.y;
}
}
}
}
Trait Implementations§
source§impl<E> SystemParam for EventWriter<'_, E>where
E: Event,
impl<E> SystemParam for EventWriter<'_, E>where
E: Event,
§type Item<'w, 's> = EventWriter<'w, E>
type Item<'w, 's> = EventWriter<'w, E>
Self
, instantiated with new lifetimes. Read moresource§fn init_state(
world: &mut World,
system_meta: &mut SystemMeta
) -> <EventWriter<'_, E> as SystemParam>::State
fn init_state( world: &mut World, system_meta: &mut SystemMeta ) -> <EventWriter<'_, E> as SystemParam>::State
World
access used by this SystemParam
and creates a new instance of this param’s State
.source§fn new_archetype(
state: &mut <EventWriter<'_, E> as SystemParam>::State,
archetype: &Archetype,
system_meta: &mut SystemMeta
)
fn new_archetype( state: &mut <EventWriter<'_, E> as SystemParam>::State, archetype: &Archetype, system_meta: &mut SystemMeta )
Archetype
, registers the components accessed by this SystemParam
(if applicable).source§fn apply(
state: &mut <EventWriter<'_, E> as SystemParam>::State,
system_meta: &SystemMeta,
world: &mut World
)
fn apply( state: &mut <EventWriter<'_, E> as SystemParam>::State, system_meta: &SystemMeta, world: &mut World )
SystemParam
’s state.
This is used to apply Commands
during apply_deferred
.source§unsafe fn get_param<'w, 's>(
state: &'s mut <EventWriter<'_, E> as SystemParam>::State,
system_meta: &SystemMeta,
world: UnsafeWorldCell<'w>,
change_tick: Tick
) -> <EventWriter<'_, E> as SystemParam>::Item<'w, 's>
unsafe fn get_param<'w, 's>( state: &'s mut <EventWriter<'_, E> as SystemParam>::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, change_tick: Tick ) -> <EventWriter<'_, E> as SystemParam>::Item<'w, 's>
SystemParamFunction
. Read moreimpl<'w, 's, E> ReadOnlySystemParam for EventWriter<'w, E>
Auto Trait Implementations§
impl<'w, E> Freeze for EventWriter<'w, E>
impl<'w, E> RefUnwindSafe for EventWriter<'w, E>
impl<'w, E> Send for EventWriter<'w, E>
impl<'w, E> Sync for EventWriter<'w, E>
impl<'w, E> Unpin for EventWriter<'w, E>
impl<'w, E> !UnwindSafe for EventWriter<'w, E>
Blanket Implementations§
source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U
T
ShaderType
for self
. When used in AsBindGroup
derives, it is safe to assume that all images in self
exist.source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.