From d9780b5e3370eb950368d3a03f5490645eaf0a06 Mon Sep 17 00:00:00 2001 From: Shane Celis Date: Wed, 22 Jan 2025 16:23:47 -0500 Subject: [PATCH 1/2] feature: Add with_or_insert_component_mut(). --- .../src/bindings/world.rs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/bevy_mod_scripting_core/src/bindings/world.rs b/crates/bevy_mod_scripting_core/src/bindings/world.rs index 2921db9a0e..4ddc679358 100644 --- a/crates/bevy_mod_scripting_core/src/bindings/world.rs +++ b/crates/bevy_mod_scripting_core/src/bindings/world.rs @@ -327,6 +327,27 @@ impl<'w> WorldAccessGuard<'w> { ) } + /// Safey modify or insert a component by claiming and releasing global access. + pub fn with_or_insert_component_mut(&self, + entity: Entity, + f: F, + ) -> Result + where + T: Component + Default, + F: FnOnce(&mut T) -> O, + { + self.with_global_access(|world| match world.get_mut::(entity) { + Some(mut component) => f(&mut component), + None => { + let mut component = T::default(); + let mut commands = world.commands(); + let result = f(&mut component); + commands.entity(entity).insert(component); + result + } + }) + } + /// Try to lookup a function with the given name on the given type id's namespaces. /// /// Returns the function if found, otherwise returns the name of the function that was not found. From b9a75567b37404c846d7658f003a641594dfa12e Mon Sep 17 00:00:00 2001 From: Shane Celis Date: Wed, 22 Jan 2025 16:24:02 -0500 Subject: [PATCH 2/2] doc: Remove comment on panic. Accepts Option<&T>. Should not panic if component is not available. --- crates/bevy_mod_scripting_core/src/bindings/world.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/crates/bevy_mod_scripting_core/src/bindings/world.rs b/crates/bevy_mod_scripting_core/src/bindings/world.rs index 4ddc679358..0b9cea8d42 100644 --- a/crates/bevy_mod_scripting_core/src/bindings/world.rs +++ b/crates/bevy_mod_scripting_core/src/bindings/world.rs @@ -283,9 +283,6 @@ impl<'w> WorldAccessGuard<'w> { } /// Safely accesses the component by claiming and releasing access to it. - /// - /// # Panics - /// - if the component does not exist pub fn with_component(&self, entity: Entity, f: F) -> Result where T: Component, @@ -305,9 +302,6 @@ impl<'w> WorldAccessGuard<'w> { } /// Safely accesses the component by claiming and releasing access to it. - /// - /// # Panics - /// - if the component does not exist pub fn with_component_mut(&self, entity: Entity, f: F) -> Result where T: Component,