Skip to content

Commit 9ffba9b

Browse files
committed
Allow returning a value from EntityMut::world_scope (#7385)
# Objective The function `EntityMut::world_scope` is a safe abstraction that allows you to temporarily get mutable access to the underlying `World` of an `EntityMut`. This function is purely stateful, meaning it is not easily possible to return a value from it. ## Solution Allow returning a computed value from the closure. This is similar to how `World::resource_scope` works. --- ## Changelog - The function `EntityMut::world_scope` now allows returning a value from the immediately-computed closure.
1 parent 27c4eaa commit 9ffba9b

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

crates/bevy_ecs/src/world/entity_ref.rs

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -540,9 +540,33 @@ impl<'w> EntityMut<'w> {
540540
}
541541

542542
/// Gives mutable access to this `EntityMut`'s [`World`] in a temporary scope.
543-
pub fn world_scope(&mut self, f: impl FnOnce(&mut World)) {
544-
f(self.world);
543+
/// This is a safe alternative to using [`Self::world_mut`].
544+
///
545+
/// # Examples
546+
///
547+
/// ```
548+
/// # use bevy_ecs::prelude::*;
549+
/// #[derive(Resource, Default, Clone, Copy)]
550+
/// struct R(u32);
551+
///
552+
/// # let mut world = World::new();
553+
/// # world.init_resource::<R>();
554+
/// # let mut entity = world.spawn_empty();
555+
/// // This closure gives us temporary access to the world.
556+
/// let new_r = entity.world_scope(|world: &mut World| {
557+
/// // Mutate the world while we have access to it.
558+
/// let mut r = world.resource_mut::<R>();
559+
/// r.0 += 1;
560+
///
561+
/// // Return a value from the world before giving it back to the `EntityMut`.
562+
/// *r
563+
/// });
564+
/// # assert_eq!(new_r.0, 1);
565+
/// ```
566+
pub fn world_scope<U>(&mut self, f: impl FnOnce(&mut World) -> U) -> U {
567+
let val = f(self.world);
545568
self.update_location();
569+
val
546570
}
547571

548572
/// Updates the internal entity location to match the current location in the internal

0 commit comments

Comments
 (0)