From cdcb773e9b04382fb1fceda04236439946e79353 Mon Sep 17 00:00:00 2001 From: Jonathan Chan Kwan Yin Date: Tue, 6 May 2025 08:19:56 +0800 Subject: [PATCH] Add `EntityWorldMut::reborrow_scope()` (#18730) # Objective Allow `EntityCommand` implementors to delegate to other entity commands easily: ```rs impl EntityCommand for Foo { fn apply(self, mut entity: EntityWorldMut) { entity.reborrow_scope(|e| StepOne.apply(e)); entity.reborrow_scope(|e| StepTwo.apply(e)); } } ``` --- crates/bevy_ecs/src/world/entity_ref.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/crates/bevy_ecs/src/world/entity_ref.rs b/crates/bevy_ecs/src/world/entity_ref.rs index 4303fef4aa..f711c7d270 100644 --- a/crates/bevy_ecs/src/world/entity_ref.rs +++ b/crates/bevy_ecs/src/world/entity_ref.rs @@ -2811,6 +2811,22 @@ impl<'w> EntityWorldMut<'w> { .entity_get_spawned_or_despawned_by(self.entity) .map(|location| location.unwrap()) } + + /// Reborrows this entity in a temporary scope. + /// This is useful for executing a function that requires a `EntityWorldMut` + /// but you do not want to move out the entity ownership. + pub fn reborrow_scope(&mut self, f: impl FnOnce(EntityWorldMut) -> U) -> U { + let Self { + entity, location, .. + } = *self; + self.world_scope(move |world| { + f(EntityWorldMut { + world, + entity, + location, + }) + }) + } } /// A view into a single entity and component in a world, which may either be vacant or occupied.