diff --git a/crates/bevy_ecs/src/resource/resources.rs b/crates/bevy_ecs/src/resource/resources.rs index 38123b09f63db..a09d4697401e3 100644 --- a/crates/bevy_ecs/src/resource/resources.rs +++ b/crates/bevy_ecs/src/resource/resources.rs @@ -345,6 +345,10 @@ impl Resources { resource_data.storage.clear_trackers(); } } + + pub fn remove(&mut self) { + self.resource_data.remove(&TypeId::of::()); + } } unsafe impl Send for Resources {} @@ -534,6 +538,8 @@ mod tests { 222 ); assert_eq!(*resources.get::().expect("resource exists"), 123); + resources.remove::(); + assert!(resources.get::().is_none()); } #[test] diff --git a/crates/bevy_ecs/src/system/commands.rs b/crates/bevy_ecs/src/system/commands.rs index 954f7e934547f..528c2d74eb11d 100644 --- a/crates/bevy_ecs/src/system/commands.rs +++ b/crates/bevy_ecs/src/system/commands.rs @@ -165,6 +165,16 @@ impl Command for InsertResource { } } +pub struct RemoveResource { + phantom: PhantomData, +} + +impl Command for RemoveResource { + fn write(self: Box, _world: &mut World, resources: &mut Resources) { + resources.remove::(); + } +} + #[derive(Debug)] pub(crate) struct InsertLocalResource { resource: T, @@ -304,6 +314,12 @@ impl Commands { }) } + pub fn remove_resource(&mut self) -> &mut Self { + self.add_command(RemoveResource:: { + phantom: PhantomData, + }) + } + /// Adds a bundle of components to the current entity. /// /// See [`Self::with`], [`Self::current_entity`]. @@ -411,6 +427,7 @@ impl Commands { #[cfg(test)] mod tests { use crate::{resource::Resources, Commands, World}; + use core::any::TypeId; #[test] fn command_buffer() { @@ -466,4 +483,34 @@ mod tests { let results_after_u64 = world.query::<&u64>().map(|a| *a).collect::>(); assert_eq!(results_after_u64, vec![]); } + + #[test] + fn remove_resources() { + let mut world = World::default(); + let mut resources = Resources::default(); + let mut command_buffer = Commands::default(); + command_buffer.insert_resource(123); + command_buffer.insert_resource(456.0); + command_buffer.apply(&mut world, &mut resources); + assert_eq!( + resources.resource_data.contains_key(&TypeId::of::()), + true + ); + assert_eq!( + resources.resource_data.contains_key(&TypeId::of::()), + true + ); + + // test resource removal + command_buffer.remove_resource::(); + command_buffer.apply(&mut world, &mut resources); + assert_eq!( + resources.resource_data.contains_key(&TypeId::of::()), + false + ); + assert_eq!( + resources.resource_data.contains_key(&TypeId::of::()), + true + ); + } }