From b58eda01e2ce6638e50285946aa7d86ba671f2c1 Mon Sep 17 00:00:00 2001 From: Jean Mertz Date: Wed, 29 Jan 2025 18:36:02 +0100 Subject: [PATCH] feat(ecs): add `EntityEntryCommands::entity()` method chaining (#17580) This allows you to continue chaining method calls after calling `EntityCommands::entry`: ```rust commands .entity(player.entity) .entry::() // Modify the component if it exists .and_modify(|mut lvl| lvl.0 += 1) // Otherwise insert a default value .or_insert(Level(0)) // Return the EntityCommands for the entity .entity() // And continue chaining method calls .insert(Name::new("Player")); ``` --------- Signed-off-by: Jean Mertz --- crates/bevy_ecs/src/system/commands/mod.rs | 36 ++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index 3748c5c1fb..a4c5ecc7ba 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -2169,6 +2169,38 @@ impl<'a, T: Component> EntityEntryCommands<'a, T> { .queue(entity_command::insert_from_world::(InsertMode::Keep)); self } + + /// Get the [`EntityCommands`] from which the [`EntityEntryCommands`] was initiated. + /// + /// This allows you to continue chaining method calls after calling [`EntityCommands::entry`]. + /// + /// # Example + /// + /// ``` + /// # use bevy_ecs::prelude::*; + /// # #[derive(Resource)] + /// # struct PlayerEntity { entity: Entity } + /// #[derive(Component)] + /// struct Level(u32); + /// + /// fn level_up_system(mut commands: Commands, player: Res) { + /// commands + /// .entity(player.entity) + /// .entry::() + /// // Modify the component if it exists + /// .and_modify(|mut lvl| lvl.0 += 1) + /// // Otherwise insert a default value + /// .or_insert(Level(0)) + /// // Return the EntityCommands for the entity + /// .entity() + /// // And continue chaining method calls + /// .insert(Name::new("Player")); + /// } + /// # bevy_ecs::system::assert_is_system(level_up_system); + /// ``` + pub fn entity(&mut self) -> EntityCommands { + self.entity_commands.reborrow() + } } #[cfg(test)] @@ -2258,6 +2290,10 @@ mod tests { commands.entity(entity).entry::>().or_from_world(); queue.apply(&mut world); assert_eq!("*****", &world.get::>(entity).unwrap().0); + let mut commands = Commands::new(&mut queue, &world); + let id = commands.entity(entity).entry::>().entity().id(); + queue.apply(&mut world); + assert_eq!(id, entity); } #[test]