@@ -283,9 +283,6 @@ impl<'w> WorldAccessGuard<'w> {
283283 }
284284
285285 /// Safely accesses the component by claiming and releasing access to it.
286- ///
287- /// # Panics
288- /// - if the component does not exist
289286 pub fn with_component < F , T , O > ( & self , entity : Entity , f : F ) -> Result < O , InteropError >
290287 where
291288 T : Component ,
@@ -305,9 +302,6 @@ impl<'w> WorldAccessGuard<'w> {
305302 }
306303
307304 /// Safely accesses the component by claiming and releasing access to it.
308- ///
309- /// # Panics
310- /// - if the component does not exist
311305 pub fn with_component_mut < F , T , O > ( & self , entity : Entity , f : F ) -> Result < O , InteropError >
312306 where
313307 T : Component ,
@@ -327,6 +321,27 @@ impl<'w> WorldAccessGuard<'w> {
327321 )
328322 }
329323
324+ /// Safey modify or insert a component by claiming and releasing global access.
325+ pub fn with_or_insert_component_mut < F , T , O > ( & self ,
326+ entity : Entity ,
327+ f : F ,
328+ ) -> Result < O , InteropError >
329+ where
330+ T : Component + Default ,
331+ F : FnOnce ( & mut T ) -> O ,
332+ {
333+ self . with_global_access ( |world| match world. get_mut :: < T > ( entity) {
334+ Some ( mut component) => f ( & mut component) ,
335+ None => {
336+ let mut component = T :: default ( ) ;
337+ let mut commands = world. commands ( ) ;
338+ let result = f ( & mut component) ;
339+ commands. entity ( entity) . insert ( component) ;
340+ result
341+ }
342+ } )
343+ }
344+
330345 /// Try to lookup a function with the given name on the given type id's namespaces.
331346 ///
332347 /// Returns the function if found, otherwise returns the name of the function that was not found.
0 commit comments