Spawn batch with relationship #19519
Open
+41
−10
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Objective
Fixes #19356
Issue: Spawning a batch of entities in relationship with the same target adds the relationship between the target and only the last entity of the batch.
spawn_batch
flushes only after having spawned all entities. This means each spawned entity will have run theon_insert
hook of itsRelationship
component. Here is the relevant part of that hook:Given the above snippet and since there's no flush between spawns, each entity finds the target without a
RelationshipTarget
component and defers the insertion of that component with the entity's id as the sole member of its collection. When the commands are finally flushed, each insertion after the first replaces the one before and in the process triggers theon_replace
hook ofRelationshipTarget
which removes theRelationship
component from the corresponding entity. That's how we end up in the invalid state.Solution
I see two possible solutions
I don't know enough about bevy as a whole but 2. seems much more efficient to me. This is what I'm proposing here. I have a doubt though because I've started to look at #19348 that 1. would fix as well.
Testing
I added a test for the issue. I've put it in
relationship/mod.rs
but I could see it inworld/spawn_batch.rs
orlib.rs
because the test is as much aboutspawn_batch
as it is about relationships.