Skip to content

Add spawn callback for scene entities #4933

@Shatur

Description

@Shatur

What problem does this solve or what need does it fill?

When spawning a scene, you often need to add additional components. For example, generate a collision from a mesh or assign a collision group.

What solution would you like?

It would be great to be able to specify a closure with EntityCommands
and EntityRef as arguments which will be called for each spawned entity from scene.

So I would suggest adding a bean called SceneHook with a closure that users can assign on scenes. For convenience, I would add it to SceneBundle introduced in #2424.

Example:

commands.spawn_bundle(SceneBundle {
    scene: asset_server.load("models/FlightHelmet/FlightHelmet.gltf#Scene0"),
    hook: SceneHook::new(|entity_ref, entity_commands| {
        if let Some(mesh) = entity_ref.get::<Mesh>() {
            // Entity have mesh, let's assign collision:
            entity_commands.insert(RigidBody::Fixed);
            entity_commands.insert(Collider::from_bevy_mesh(mesh));
        } else if let Some(name) = entity_ref.get::<Name>() {
            // Can insert some components based on name
        }
    }),
    ..Default::default()
});

What alternative(s) have you considered?

But both approaches require adding a separate system for each scene for which you need to add components after spawn. Also it forces user to create a separate component for each scene to somehow differentiate events or added SceneRoots in "post-spawn" systems.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ScenesComposing and serializing ECS objectsC-FeatureA new feature, making something new possible

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions