Skip to content

Commit bd7dcd3

Browse files
lee-orrBD103
andauthored
deregister events (#14083)
# Objective Add ability to de-register events from the EventRegistry (and the associated World). The initial reasoning relates to retaining support for Event hot reloading in `dexterous_developer`. ## Solution Add a `deregister_events<T: Event>(&mut world)` method to the `EventRegistry` struct. ## Testing Added an automated test that verifies the event registry adds and removes `Events<T>` from the world. --------- Co-authored-by: BD103 <[email protected]>
1 parent 856b39d commit bd7dcd3

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

crates/bevy_ecs/src/event/mod.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,24 @@ mod tests {
280280
assert!(is_empty, "EventReader should be empty");
281281
}
282282

283+
#[test]
284+
fn test_event_registry_can_add_and_remove_events_to_world() {
285+
use bevy_ecs::prelude::*;
286+
287+
let mut world = World::new();
288+
EventRegistry::register_event::<TestEvent>(&mut world);
289+
290+
let has_events = world.get_resource::<Events<TestEvent>>().is_some();
291+
292+
assert!(has_events, "Should have the events resource");
293+
294+
EventRegistry::deregister_events::<TestEvent>(&mut world);
295+
296+
let has_events = world.get_resource::<Events<TestEvent>>().is_some();
297+
298+
assert!(!has_events, "Should not have the events resource");
299+
}
300+
283301
#[test]
284302
fn test_update_drain() {
285303
let mut events = Events::<TestEvent>::default();

crates/bevy_ecs/src/event/registry.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,10 @@ pub enum ShouldUpdateEvents {
4141
}
4242

4343
impl EventRegistry {
44-
/// Registers an event type to be updated.
44+
/// Registers an event type to be updated in a given [`World`]
45+
///
46+
/// If no instance of the [`EventRegistry`] exists in the world, this will add one - otherwise it will use
47+
/// the existing instance.
4548
pub fn register_event<T: Event>(world: &mut World) {
4649
// By initializing the resource here, we can be sure that it is present,
4750
// and receive the correct, up-to-date `ComponentId` even if it was previously removed.
@@ -77,4 +80,14 @@ impl EventRegistry {
7780
}
7881
}
7982
}
83+
84+
/// Removes an event from the world and it's associated [`EventRegistry`].
85+
pub fn deregister_events<T: Event>(world: &mut World) {
86+
let component_id = world.init_resource::<Events<T>>();
87+
let mut registry = world.get_resource_or_insert_with(Self::default);
88+
registry
89+
.event_updates
90+
.retain(|e| e.component_id != component_id);
91+
world.remove_resource::<Events<T>>();
92+
}
8093
}

0 commit comments

Comments
 (0)