Struct bevy::ecs::event::EventReader

pub struct EventReader<'w, 's, E>
where E: Event,
{ /* private fields */ }
Expand description

Reads events of type T in order and tracks which events have already been read.

§Concurrency

Unlike EventWriter<T>, systems with EventReader<T> param can be executed concurrently (but not concurrently with EventWriter<T> systems for the same event type).

Implementations§

§

impl<'w, 's, E> EventReader<'w, 's, E>
where E: Event,

pub fn read(&mut self) -> EventIterator<'_, E>

Iterates over the events this EventReader has not seen yet. This updates the EventReader’s event counter, which means subsequent event reads will not include events that happened before now.

Examples found in repository?
examples/ecs/send_and_receive_events.rs (line 62)
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
Hide additional examples
examples/ecs/event.rs (line 54)
53
54
55
56
57
58
59
60
61
62
63
fn event_listener(mut events: EventReader<MyEvent>) {
    for my_event in events.read() {
        info!("{}", my_event.message);
    }
}

fn sound_player(mut play_sound_events: EventReader<PlaySound>) {
    for _ in play_sound_events.read() {
        info!("Playing a sound");
    }
}
examples/app/drag_and_drop.rs (line 13)
12
13
14
15
16
fn file_drag_and_drop_system(mut events: EventReader<FileDragAndDrop>) {
    for event in events.read() {
        info!("{:?}", event);
    }
}
examples/input/touch_input_events.rs (line 13)
12
13
14
15
16
fn touch_event_system(mut touch_events: EventReader<TouchInput>) {
    for event in touch_events.read() {
        info!("{:?}", event);
    }
}
examples/input/keyboard_input_events.rs (line 14)
13
14
15
16
17
fn print_keyboard_event_system(mut keyboard_input_events: EventReader<KeyboardInput>) {
    for event in keyboard_input_events.read() {
        info!("{:?}", event);
    }
}
examples/input/char_input_events.rs (line 14)
13
14
15
16
17
fn print_char_event_system(mut char_input_events: EventReader<ReceivedCharacter>) {
    for event in char_input_events.read() {
        info!("{:?}: '{}'", event, event.char);
    }
}

pub fn read_with_id(&mut self) -> EventIteratorWithId<'_, E>

Like read, except also returning the EventId of the events.

pub fn par_read(&mut self) -> EventParIter<'_, E>

Returns a parallel iterator over the events this EventReader has not seen yet. See also for_each.

§Example

#[derive(Event)]
struct MyEvent {
    value: usize,
}

#[derive(Resource, Default)]
struct Counter(AtomicUsize);

// setup
let mut world = World::new();
world.init_resource::<Events<MyEvent>>();
world.insert_resource(Counter::default());

let mut schedule = Schedule::default();
schedule.add_systems(|mut events: EventReader<MyEvent>, counter: Res<Counter>| {
    events.par_read().for_each(|MyEvent { value }| {
        counter.0.fetch_add(*value, Ordering::Relaxed);
    });
});
for value in 0..100 {
    world.send_event(MyEvent { value });
}
schedule.run(&mut world);
let Counter(counter) = world.remove_resource::<Counter>().unwrap();
// all events were processed
assert_eq!(counter.into_inner(), 4950);

pub fn len(&self) -> usize

Determines the number of events available to be read from this EventReader without consuming any.

pub fn is_empty(&self) -> bool

Returns true if there are no events available to read.

§Example

The following example shows a useful pattern where some behavior is triggered if new events are available. EventReader::clear() is used so the same events don’t re-trigger the behavior the next time the system runs.

#[derive(Event)]
struct CollisionEvent;

fn play_collision_sound(mut events: EventReader<CollisionEvent>) {
    if !events.is_empty() {
        events.clear();
        // Play a sound
    }
}
Examples found in repository?
examples/games/breakout.rs (line 420)
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
fn play_collision_sound(
    mut commands: Commands,
    mut collision_events: EventReader<CollisionEvent>,
    sound: Res<CollisionSound>,
) {
    // Play a sound once per frame if a collision occurred.
    if !collision_events.is_empty() {
        // This prevents events staying active on the next frame.
        collision_events.clear();
        commands.spawn(AudioBundle {
            source: sound.clone(),
            // auto-despawn the entity when playback finishes
            settings: PlaybackSettings::DESPAWN,
        });
    }
}
More examples
Hide additional examples
examples/asset/processing/asset_processing.rs (line 236)
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
fn print_text(
    handles: Res<TextAssets>,
    texts: Res<Assets<Text>>,
    mut asset_events: EventReader<AssetEvent<Text>>,
) {
    if !asset_events.is_empty() {
        // This prints the current values of the assets
        // Hot-reloading is supported, so try modifying the source assets (and their meta files)!
        println!("Current Values:");
        println!("  a: {:?}", texts.get(&handles.a));
        println!("  b: {:?}", texts.get(&handles.b));
        println!("  c: {:?}", texts.get(&handles.c));
        println!("  d: {:?}", texts.get(&handles.d));
        println!("  e: {:?}", texts.get(&handles.e));
        println!("(You can modify source assets and their .meta files to hot-reload changes!)");
        println!();
        asset_events.clear();
    }
}

pub fn clear(&mut self)

Consumes all available events.

This means these events will not appear in calls to EventReader::read() or EventReader::read_with_id() and EventReader::is_empty() will return true.

For usage, see EventReader::is_empty().

Examples found in repository?
examples/games/breakout.rs (line 422)
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
fn play_collision_sound(
    mut commands: Commands,
    mut collision_events: EventReader<CollisionEvent>,
    sound: Res<CollisionSound>,
) {
    // Play a sound once per frame if a collision occurred.
    if !collision_events.is_empty() {
        // This prevents events staying active on the next frame.
        collision_events.clear();
        commands.spawn(AudioBundle {
            source: sound.clone(),
            // auto-despawn the entity when playback finishes
            settings: PlaybackSettings::DESPAWN,
        });
    }
}
More examples
Hide additional examples
examples/asset/processing/asset_processing.rs (line 247)
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
fn print_text(
    handles: Res<TextAssets>,
    texts: Res<Assets<Text>>,
    mut asset_events: EventReader<AssetEvent<Text>>,
) {
    if !asset_events.is_empty() {
        // This prints the current values of the assets
        // Hot-reloading is supported, so try modifying the source assets (and their meta files)!
        println!("Current Values:");
        println!("  a: {:?}", texts.get(&handles.a));
        println!("  b: {:?}", texts.get(&handles.b));
        println!("  c: {:?}", texts.get(&handles.c));
        println!("  d: {:?}", texts.get(&handles.d));
        println!("  e: {:?}", texts.get(&handles.e));
        println!("(You can modify source assets and their .meta files to hot-reload changes!)");
        println!();
        asset_events.clear();
    }
}
examples/3d/../helpers/camera_controller.rs (line 123)
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
fn run_camera_controller(
    time: Res<Time>,
    mut windows: Query<&mut Window>,
    mut mouse_events: EventReader<MouseMotion>,
    mut scroll_events: EventReader<MouseWheel>,
    mouse_button_input: Res<ButtonInput<MouseButton>>,
    key_input: Res<ButtonInput<KeyCode>>,
    mut toggle_cursor_grab: Local<bool>,
    mut mouse_cursor_grab: Local<bool>,
    mut query: Query<(&mut Transform, &mut CameraController), With<Camera>>,
) {
    let dt = time.delta_seconds();

    if let Ok((mut transform, mut controller)) = query.get_single_mut() {
        if !controller.initialized {
            let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
            controller.yaw = yaw;
            controller.pitch = pitch;
            controller.initialized = true;
            info!("{}", *controller);
        }
        if !controller.enabled {
            mouse_events.clear();
            return;
        }

        let mut scroll = 0.0;
        for scroll_event in scroll_events.read() {
            let amount = match scroll_event.unit {
                MouseScrollUnit::Line => scroll_event.y,
                MouseScrollUnit::Pixel => scroll_event.y / 16.0,
            };
            scroll += amount;
        }
        controller.walk_speed += scroll * controller.scroll_factor * controller.walk_speed;
        controller.run_speed = controller.walk_speed * 3.0;

        // Handle key input
        let mut axis_input = Vec3::ZERO;
        if key_input.pressed(controller.key_forward) {
            axis_input.z += 1.0;
        }
        if key_input.pressed(controller.key_back) {
            axis_input.z -= 1.0;
        }
        if key_input.pressed(controller.key_right) {
            axis_input.x += 1.0;
        }
        if key_input.pressed(controller.key_left) {
            axis_input.x -= 1.0;
        }
        if key_input.pressed(controller.key_up) {
            axis_input.y += 1.0;
        }
        if key_input.pressed(controller.key_down) {
            axis_input.y -= 1.0;
        }

        let mut cursor_grab_change = false;
        if key_input.just_pressed(controller.keyboard_key_toggle_cursor_grab) {
            *toggle_cursor_grab = !*toggle_cursor_grab;
            cursor_grab_change = true;
        }
        if mouse_button_input.just_pressed(controller.mouse_key_cursor_grab) {
            *mouse_cursor_grab = true;
            cursor_grab_change = true;
        }
        if mouse_button_input.just_released(controller.mouse_key_cursor_grab) {
            *mouse_cursor_grab = false;
            cursor_grab_change = true;
        }
        let cursor_grab = *mouse_cursor_grab || *toggle_cursor_grab;

        // Apply movement update
        if axis_input != Vec3::ZERO {
            let max_speed = if key_input.pressed(controller.key_run) {
                controller.run_speed
            } else {
                controller.walk_speed
            };
            controller.velocity = axis_input.normalize() * max_speed;
        } else {
            let friction = controller.friction.clamp(0.0, 1.0);
            controller.velocity *= 1.0 - friction;
            if controller.velocity.length_squared() < 1e-6 {
                controller.velocity = Vec3::ZERO;
            }
        }
        let forward = *transform.forward();
        let right = *transform.right();
        transform.translation += controller.velocity.x * dt * right
            + controller.velocity.y * dt * Vec3::Y
            + controller.velocity.z * dt * forward;

        // Handle cursor grab
        if cursor_grab_change {
            if cursor_grab {
                for mut window in &mut windows {
                    if !window.focused {
                        continue;
                    }

                    window.cursor.grab_mode = CursorGrabMode::Locked;
                    window.cursor.visible = false;
                }
            } else {
                for mut window in &mut windows {
                    window.cursor.grab_mode = CursorGrabMode::None;
                    window.cursor.visible = true;
                }
            }
        }

        // Handle mouse input
        let mut mouse_delta = Vec2::ZERO;
        if cursor_grab {
            for mouse_event in mouse_events.read() {
                mouse_delta += mouse_event.delta;
            }
        } else {
            mouse_events.clear();
        }

        if mouse_delta != Vec2::ZERO {
            // Apply look update
            controller.pitch = (controller.pitch
                - mouse_delta.y * RADIANS_PER_DOT * controller.sensitivity)
                .clamp(-PI / 2., PI / 2.);
            controller.yaw -= mouse_delta.x * RADIANS_PER_DOT * controller.sensitivity;
            transform.rotation =
                Quat::from_euler(EulerRot::ZYX, 0.0, controller.yaw, controller.pitch);
        }
    }
}

Trait Implementations§

§

impl<'w, 's, E> Debug for EventReader<'w, 's, E>
where E: Debug + Event,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<E> SystemParam for EventReader<'_, '_, E>
where E: Event,

§

type State = FetchState<E>

Used to store data which persists across invocations of a system.
§

type Item<'w, 's> = EventReader<'w, 's, E>

The item type returned when constructing this system param. The value of this associated type should be Self, instantiated with new lifetimes. Read more
§

fn init_state( world: &mut World, system_meta: &mut SystemMeta ) -> <EventReader<'_, '_, E> as SystemParam>::State

Registers any World access used by this SystemParam and creates a new instance of this param’s State.
§

unsafe fn new_archetype( state: &mut <EventReader<'_, '_, E> as SystemParam>::State, archetype: &Archetype, system_meta: &mut SystemMeta )

For the specified Archetype, registers the components accessed by this SystemParam (if applicable).a Read more
§

fn apply( state: &mut <EventReader<'_, '_, E> as SystemParam>::State, system_meta: &SystemMeta, world: &mut World )

Applies any deferred mutations stored in this SystemParam’s state. This is used to apply Commands during apply_deferred.
§

unsafe fn get_param<'w, 's>( state: &'s mut <EventReader<'_, '_, E> as SystemParam>::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, change_tick: Tick ) -> <EventReader<'_, '_, E> as SystemParam>::Item<'w, 's>

Creates a parameter to be passed into a SystemParamFunction. Read more
§

impl<'w, 's, E> ReadOnlySystemParam for EventReader<'w, 's, E>

Auto Trait Implementations§

§

impl<'w, 's, E> Freeze for EventReader<'w, 's, E>

§

impl<'w, 's, E> RefUnwindSafe for EventReader<'w, 's, E>
where E: RefUnwindSafe,

§

impl<'w, 's, E> Send for EventReader<'w, 's, E>

§

impl<'w, 's, E> Sync for EventReader<'w, 's, E>

§

impl<'w, 's, E> Unpin for EventReader<'w, 's, E>

§

impl<'w, 's, E> !UnwindSafe for EventReader<'w, 's, E>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert 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.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<S> FromSample<S> for S

§

fn from_sample_(s: S) -> S

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

§

fn into_sample(self) -> T

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

§

fn to_sample_(self) -> U

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
§

impl<T> ConditionalSend for T
where T: Send,

§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

§

impl<T> Settings for T
where T: 'static + Send + Sync,

§

impl<T> WasmNotSend for T
where T: Send,

§

impl<T> WasmNotSendSync for T
where T: WasmNotSend + WasmNotSync,

§

impl<T> WasmNotSync for T
where T: Sync,