diff --git a/crates/bevy_ecs/src/storage/resource.rs b/crates/bevy_ecs/src/storage/resource.rs index 4a9b0eb3ce4b8..f1a0e9fb53552 100644 --- a/crates/bevy_ecs/src/storage/resource.rs +++ b/crates/bevy_ecs/src/storage/resource.rs @@ -236,6 +236,12 @@ impl Resources { self.resources.get(component_id) } + /// Clears all resources. + #[inline] + pub fn clear(&mut self) { + self.resources.clear(); + } + /// Gets mutable access to a resource, if it exists. #[inline] pub(crate) fn get_mut(&mut self, component_id: ComponentId) -> Option<&mut ResourceData> { diff --git a/crates/bevy_ecs/src/storage/sparse_set.rs b/crates/bevy_ecs/src/storage/sparse_set.rs index cc3da14682cb9..d145122c33456 100644 --- a/crates/bevy_ecs/src/storage/sparse_set.rs +++ b/crates/bevy_ecs/src/storage/sparse_set.rs @@ -447,6 +447,12 @@ impl SparseSet { }) } + pub fn clear(&mut self) { + self.dense.clear(); + self.indices.clear(); + self.sparse.clear(); + } + pub(crate) fn into_immutable(self) -> ImmutableSparseSet { ImmutableSparseSet { dense: self.dense.into_boxed_slice(), diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index f8b41c8b34c43..066268526e953 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -1624,12 +1624,32 @@ impl World { self.last_check_tick = change_tick; } + /// Runs both [`clear_entities`](Self::clear_entities) and [`clear_resources`](Self::clear_resources), + /// invalidating all [`Entity`] and resource fetches such as [`Res`](crate::system::Res), [`ResMut`](crate::system::ResMut) + pub fn clear_all(&mut self) { + self.clear_entities(); + self.clear_resources(); + } + + /// Despawns all entities in this [`World`]. pub fn clear_entities(&mut self) { self.storages.tables.clear(); self.storages.sparse_sets.clear(); self.archetypes.clear_entities(); self.entities.clear(); } + + /// Clears all resources in this [`World`]. + /// + /// **Note:** Any resource fetch to this [World] will fail unless they are re-initialized, + /// including engine-internal resources that are only initialized on app/world construction. + /// + /// This can easily cause systems expecting certain resources to immediately start panicking. + /// Use with caution. + pub fn clear_resources(&mut self) { + self.storages.resources.clear(); + self.storages.non_send_resources.clear(); + } } impl World {