From deba691fffde8c9adf72f98421fa5f097f300553 Mon Sep 17 00:00:00 2001 From: JaySpruce Date: Wed, 2 Apr 2025 12:31:29 -0500 Subject: [PATCH] Implement `insert_children` for `EntityCommands` (#18675) Extension of #18409. I was updating a migration guide for hierarchy commands and realized `insert_children` wasn't added to `EntityCommands`, only `EntityWorldMut`. This adds that and `insert_related` (basically just some copy-and-pasting). --- crates/bevy_ecs/src/hierarchy.rs | 6 ++++++ .../src/relationship/related_methods.rs | 17 +++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/crates/bevy_ecs/src/hierarchy.rs b/crates/bevy_ecs/src/hierarchy.rs index c32bfc02b4..da92d5babb 100644 --- a/crates/bevy_ecs/src/hierarchy.rs +++ b/crates/bevy_ecs/src/hierarchy.rs @@ -361,6 +361,12 @@ impl<'a> EntityCommands<'a> { self.add_related::(children) } + /// Insert children at specific index. + /// See also [`insert_related`](Self::insert_related). + pub fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self { + self.insert_related::(index, children) + } + /// Adds the given child to this entity pub fn add_child(&mut self, child: Entity) -> &mut Self { self.add_related::(&[child]) diff --git a/crates/bevy_ecs/src/relationship/related_methods.rs b/crates/bevy_ecs/src/relationship/related_methods.rs index 445deb4a25..f48335c83b 100644 --- a/crates/bevy_ecs/src/relationship/related_methods.rs +++ b/crates/bevy_ecs/src/relationship/related_methods.rs @@ -343,6 +343,23 @@ impl<'a> EntityCommands<'a> { }) } + /// Relates the given entities to this entity with the relation `R`, starting at this particular index. + /// + /// If the `related` has duplicates, a related entity will take the index of its last occurrence in `related`. + /// If the indices go out of bounds, they will be clamped into bounds. + /// This will not re-order existing related entities unless they are in `related`. + pub fn insert_related(&mut self, index: usize, related: &[Entity]) -> &mut Self + where + ::Collection: + OrderedRelationshipSourceCollection, + { + let related: Box<[Entity]> = related.into(); + + self.queue(move |mut entity: EntityWorldMut| { + entity.insert_related::(index, &related); + }) + } + /// Relates the given entity to this with the relation `R`. /// /// See [`add_related`](Self::add_related) if you want to relate more than one entity.