@@ -1063,7 +1063,10 @@ pub enum ShouldUpdateEvents {
10631063}
10641064
10651065impl EventRegistry {
1066- /// Registers an event type to be updated.
1066+ /// Registers an event type to be updated in a given [`World`]
1067+ ///
1068+ /// If no instance of the [`EventRegistry`] exists in the world, this will add one - otherwise it will use
1069+ /// the existing instance.
10671070 pub fn register_event < T : Event > ( world : & mut World ) {
10681071 // By initializing the resource here, we can be sure that it is present,
10691072 // and receive the correct, up-to-date `ComponentId` even if it was previously removed.
@@ -1081,6 +1084,16 @@ impl EventRegistry {
10811084 } ) ;
10821085 }
10831086
1087+ /// Removes an event from the world and it's associated [`EventRegistry`].
1088+ pub fn deregister_events < T : Event > ( world : & mut World ) {
1089+ let component_id = world. init_resource :: < Events < T > > ( ) ;
1090+ let mut registry = world. get_resource_or_insert_with ( Self :: default) ;
1091+ registry
1092+ . event_updates
1093+ . retain ( |e| e. component_id != component_id) ;
1094+ world. remove_resource :: < Events < T > > ( ) ;
1095+ }
1096+
10841097 /// Updates all of the registered events in the World.
10851098 pub fn run_updates ( & mut self , world : & mut World , last_change_tick : Tick ) {
10861099 for registered_event in & mut self . event_updates {
@@ -1645,4 +1658,22 @@ mod tests {
16451658 assert_eq ! ( test_events. len( ) , 2 ) ; // Events are double-buffered, so we see 2 + 0 = 2
16461659 assert_eq ! ( test_events. iter_current_update_events( ) . count( ) , 0 ) ;
16471660 }
1661+
1662+ #[ test]
1663+ fn test_event_registry_can_add_and_remove_events_to_world ( ) {
1664+ use bevy_ecs:: prelude:: * ;
1665+
1666+ let mut world = World :: new ( ) ;
1667+ EventRegistry :: register_event :: < TestEvent > ( & mut world) ;
1668+
1669+ let has_events = world. get_resource :: < Events < TestEvent > > ( ) . is_some ( ) ;
1670+
1671+ assert ! ( has_events, "Should have the events resource" ) ;
1672+
1673+ EventRegistry :: deregister_events :: < TestEvent > ( & mut world) ;
1674+
1675+ let has_events = world. get_resource :: < Events < TestEvent > > ( ) . is_some ( ) ;
1676+
1677+ assert ! ( !has_events, "Should not have the events resource" ) ;
1678+ }
16481679}
0 commit comments