@@ -283,9 +283,6 @@ impl<'w> WorldAccessGuard<'w> {
283
283
}
284
284
285
285
/// Safely accesses the component by claiming and releasing access to it.
286
- ///
287
- /// # Panics
288
- /// - if the component does not exist
289
286
pub fn with_component < F , T , O > ( & self , entity : Entity , f : F ) -> Result < O , InteropError >
290
287
where
291
288
T : Component ,
@@ -305,9 +302,6 @@ impl<'w> WorldAccessGuard<'w> {
305
302
}
306
303
307
304
/// Safely accesses the component by claiming and releasing access to it.
308
- ///
309
- /// # Panics
310
- /// - if the component does not exist
311
305
pub fn with_component_mut < F , T , O > ( & self , entity : Entity , f : F ) -> Result < O , InteropError >
312
306
where
313
307
T : Component ,
@@ -327,6 +321,27 @@ impl<'w> WorldAccessGuard<'w> {
327
321
)
328
322
}
329
323
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
+
330
345
/// Try to lookup a function with the given name on the given type id's namespaces.
331
346
///
332
347
/// Returns the function if found, otherwise returns the name of the function that was not found.
0 commit comments