diff --git a/crates/bevy_mod_scripting_core/src/bindings/world.rs b/crates/bevy_mod_scripting_core/src/bindings/world.rs index 2921db9a0e..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, @@ -327,6 +321,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.