Skip to content

Commit d9780b5

Browse files
committed
feature: Add with_or_insert_component_mut().
1 parent c71fa0a commit d9780b5

File tree

1 file changed

+21
-0
lines changed
  • crates/bevy_mod_scripting_core/src/bindings

1 file changed

+21
-0
lines changed

crates/bevy_mod_scripting_core/src/bindings/world.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,27 @@ impl<'w> WorldAccessGuard<'w> {
327327
)
328328
}
329329

330+
/// Safey modify or insert a component by claiming and releasing global access.
331+
pub fn with_or_insert_component_mut<F, T, O>(&self,
332+
entity: Entity,
333+
f: F,
334+
) -> Result<O, InteropError>
335+
where
336+
T: Component + Default,
337+
F: FnOnce(&mut T) -> O,
338+
{
339+
self.with_global_access(|world| match world.get_mut::<T>(entity) {
340+
Some(mut component) => f(&mut component),
341+
None => {
342+
let mut component = T::default();
343+
let mut commands = world.commands();
344+
let result = f(&mut component);
345+
commands.entity(entity).insert(component);
346+
result
347+
}
348+
})
349+
}
350+
330351
/// Try to lookup a function with the given name on the given type id's namespaces.
331352
///
332353
/// Returns the function if found, otherwise returns the name of the function that was not found.

0 commit comments

Comments
 (0)