Skip to content

Panic calling DynamicScene::write_to_world with MapEntities and ComponentHooks #14300

@mrchantey

Description

@mrchantey

Bevy version

0.14.0

What you did

  • call DynamicScene::write_to_world with two components:
    1. One that uses MapEntities
    2. One that calls world.commands().spawn_empty() in ComponentHooks::on_add

What went wrong

Panics at bevy_ecs::entity::Entities::verify_flushed, traced back to scene::write_to_world

thread 'main' panicked at C:\work-ref\bevy\crates\bevy_ecs\src\entity\mod.rs:582:9:
flush() needs to be called before this operation is legal

Additional information

I dont know enough about the ecs internals to understand whats happening, possibly commands from the DeferredWorld in ComponentHooks::on_add are being called at an inappropriate time?

Full reproducible

use bevy::ecs::entity::MapEntities;
use bevy::ecs::reflect::ReflectMapEntities;
use bevy::prelude::*;

#[derive(Default, Component, Reflect)]
#[reflect(Component)]
struct CompA;
#[derive(Component, Reflect)]
// #[reflect(Component)]             // OK
#[reflect(Component, MapEntities)]   // Breaks
struct CompB(pub Entity);

impl MapEntities for CompB {
  fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {
    self.0 = entity_mapper.map_entity(self.0);
  }
}

fn main() {
  let mut app = App::new();
  app.register_type::<CompA>().register_type::<CompB>();
  let world = app.world_mut();
  world
    .register_component_hooks::<CompA>()
    .on_add(|mut world, _, _| {
      world
        .commands()
        .spawn_empty();
    });
  world.spawn((CompB(Entity::PLACEHOLDER), CompA));

  let scene = DynamicScene::from_world(world);
  scene.write_to_world(world, &mut default()).unwrap();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ECSEntities, components, systems, and eventsA-ScenesComposing and serializing ECS objectsC-BugAn unexpected or incorrect behaviorS-Needs-DesignThis issue requires design work to think about how it would best be accomplished

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions