diff --git a/crates/bevy_ecs/src/event/mod.rs b/crates/bevy_ecs/src/event/mod.rs index 5f24f54151..a959fd5e77 100644 --- a/crates/bevy_ecs/src/event/mod.rs +++ b/crates/bevy_ecs/src/event/mod.rs @@ -280,6 +280,24 @@ mod tests { assert!(is_empty, "EventReader should be empty"); } + #[test] + fn test_event_registry_can_add_and_remove_events_to_world() { + use bevy_ecs::prelude::*; + + let mut world = World::new(); + EventRegistry::register_event::(&mut world); + + let has_events = world.get_resource::>().is_some(); + + assert!(has_events, "Should have the events resource"); + + EventRegistry::deregister_events::(&mut world); + + let has_events = world.get_resource::>().is_some(); + + assert!(!has_events, "Should not have the events resource"); + } + #[test] fn test_update_drain() { let mut events = Events::::default(); diff --git a/crates/bevy_ecs/src/event/registry.rs b/crates/bevy_ecs/src/event/registry.rs index 2904214bde..67061f2212 100644 --- a/crates/bevy_ecs/src/event/registry.rs +++ b/crates/bevy_ecs/src/event/registry.rs @@ -41,7 +41,10 @@ pub enum ShouldUpdateEvents { } impl EventRegistry { - /// Registers an event type to be updated. + /// Registers an event type to be updated in a given [`World`] + /// + /// If no instance of the [`EventRegistry`] exists in the world, this will add one - otherwise it will use + /// the existing instance. pub fn register_event(world: &mut World) { // By initializing the resource here, we can be sure that it is present, // and receive the correct, up-to-date `ComponentId` even if it was previously removed. @@ -77,4 +80,14 @@ impl EventRegistry { } } } + + /// Removes an event from the world and it's associated [`EventRegistry`]. + pub fn deregister_events(world: &mut World) { + let component_id = world.init_resource::>(); + let mut registry = world.get_resource_or_insert_with(Self::default); + registry + .event_updates + .retain(|e| e.component_id != component_id); + world.remove_resource::>(); + } }