Skip to content

Latest commit

 

History

History
93 lines (70 loc) · 3.41 KB

custom_events.md

File metadata and controls

93 lines (70 loc) · 3.41 KB

Custom Events

In addition to the build-in Events, we can create our own Events.

In the following example, we will trigger our own Event when we press the key space. This Event will be received by another system, where we will print the content of the Event.

To create an Event, we make a struct to derive Event.

#[derive(Event)]
struct MyEvent(u32);

MyEvent contains an unsigned 32-bit integer as its content.

This Event must be added to the App.

App::new().add_event::<MyEvent>()

To trigger the Event, we include the system parameter EventWriter<MyEvent>.

fn handle_keys(keyboard_input: Res<Input<KeyCode>>, mut events: EventWriter<MyEvent>) {
    if keyboard_input.just_pressed(KeyCode::Space) {
        events.send(MyEvent(99));
    }
}

We use the method send of EventWriter<MyEvent> to send the Event.

To receive the Event, we refer to the system parameter EventReader<MyEvent>.

fn handle_my_events(mut events: EventReader<MyEvent>) {
    for my_event in events.read() {
        println!("{}", my_event.0);
    }
}

We use the method read of EventReader<MyEvent> to receive the Event. Then we print the content of the Event.

The full code is as follows:

use bevy::{
    app::{App, Update},
    ecs::{
        event::{Event, EventReader, EventWriter},
        system::Res,
    },
    input::{keyboard::KeyCode, Input},
    DefaultPlugins,
};

#[derive(Event)]
struct MyEvent(u32);

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_event::<MyEvent>()
        .add_systems(Update, (handle_keys, handle_my_events))
        .run();
}

fn handle_keys(keyboard_input: Res<Input<KeyCode>>, mut events: EventWriter<MyEvent>) {
    if keyboard_input.just_pressed(KeyCode::Space) {
        events.send(MyEvent(99));
    }
}

fn handle_my_events(mut events: EventReader<MyEvent>) {
    for my_event in events.read() {
        println!("{}", my_event.0);
    }
}

When we press the key space, we get the output:

99

➡️ Next: Turning On/Off A System

📘 Back: Table of contents