spawn_batch creates incorrect relationships when RelationshipTarget is initially empty
- Dominant language
- Rust
- Stars
- 48.2k
- Forks
- 4.8k
- Avg merge
- 3d 22h
- Merged PRs (30d)
- 161
Description
## Bevy version
_The release number or commit hash of the version you're using_: [45ba5b9f0347710d0b84979631fae6f690434d62](https://github.com/bevyengine/bevy/tree/45ba5b9f0347710d0b84979631fae6f690434d62)
## What you did
This test is failing:
```rust
#[test]
fn spawn_batch() {
#[derive(Component)]
#[relationship(relationship_target = LikedBy)]
struct Likes(pub Entity);
#[derive(Component)]
#[relationship_target(relationship = Likes)]
struct LikedBy(Vec);
let mut world = World::new();
let a = world.spawn_empty().id();
let b = world
.spawn_batch((0..10).map(|_| Likes(a)))
.collect::>();
assert_eq!(world.entity(a).get::().unwrap().0, b);
}
```
## What went wrong
When using `World::spawn_batch` with an initially empty `RelationshipTarget`, relationships between entities are not established.
- _what were you expecting?_ Each entity in the batch should establish a proper relationship component, just like when using `World::spawn` in a loop.
- _what actually happened?_ When using `World::spawn_batch` to spawn multiple entities referencing the same target entity, and that target has no `RelationshipTarget`, each subsequent command overwrites the `RelationshipTarget` created by the previous one. This happens because `World::spawn_batch` defers commands execution, and hooks that update the `RelationshipTarget` run before previous commands are flushed. As a result, every iteration sees an empty `RelationshipTarget` on the target and reinitializes it.
## Additional information
- _workarounds that you used_:
- Spawn entities individually in a loop instead of using `spawn_batch`
- Spawn one entity first to initialize the target's relationship, then use `spawn_batch` for the rest within the same target group
Contributor guide
Assessment
This issue has not been assessed yet.