From 313db3991272980f4249d05f18369d634b61fe0a Mon Sep 17 00:00:00 2001 From: nsarlin Date: Fri, 16 Aug 2024 23:25:11 +0200 Subject: [PATCH] Add `try_insert_with_new` (#14787) # Objective Fix #14771 by adding a `try_insert_if_new` method to the `EntityCommands` ## Solution This simply calls the `try_insert` function with `InsertMode::Keep` ## Testing I did not add any test because `EntityCommands::try_insert` does not seem to be tested either. I can add some if needed. --- crates/bevy_ecs/src/system/commands/mod.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index 8dfa8ce56e..292a28ebe1 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -960,7 +960,7 @@ impl EntityCommands<'_> { /// The command will panic when applied if the associated entity does not /// exist. /// - /// To avoid a panic in this case, use the command [`Self::try_insert`] + /// To avoid a panic in this case, use the command [`Self::try_insert_if_new`] /// instead. pub fn insert_if_new(&mut self, bundle: impl Bundle) -> &mut Self { self.add(insert(bundle, InsertMode::Keep)) @@ -1065,6 +1065,19 @@ impl EntityCommands<'_> { self.add(try_insert(bundle, InsertMode::Replace)) } + /// Tries to add a [`Bundle`] of components to the entity without overwriting. + /// + /// This is the same as [`EntityCommands::try_insert`], but in case of duplicate + /// components will leave the old values instead of replacing them with new + /// ones. + /// + /// # Note + /// + /// Unlike [`Self::insert_if_new`], this will not panic if the associated entity does not exist. + pub fn try_insert_if_new(&mut self, bundle: impl Bundle) -> &mut Self { + self.add(try_insert(bundle, InsertMode::Keep)) + } + /// Removes a [`Bundle`] of components from the entity. /// /// # Example