Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Spawn a Relationship Synchronously

Bevy relationships may be spawned using specialized commands, like with_children or with_related_entities. bevy_pipe_affect APIs are more minimal, but these situations can still be handled ergonomically:

  1. Return an effect that spawns the entity that will be the RelationshipTarget with command_spawn_and. In the Parent/ChildOf relationship, this will become the Parent entity. That component does not need to be provided, it will be created by Bevy.
  2. Provide a closure to the second argument of the command_spawn_and call that returns another command_spawn- effect that will spawn the Relationship entity. In the Parent/ChildOf relationship, this is the ChildOf entity. This time, you do need to provide that component with the Entity provided to the closure (this will be RelationshipTarget Entity, spawned in step 1).

The relationship example does this, while also bundling some sprites/marker components:

#[derive(Component)] struct Spinny;
use bevy::prelude::*;
use bevy_pipe_affect::prelude::*;

fn spawn_relationship() -> impl Effect {
    // We will give both entities a sprite, which we can load using this effect
    // We can use its handle to create more effects with a closure
    asset_server_load_and("player.png", |image_handle| {
        // Similarly, this effect will spawn our components
        // Then, we use the resulting Entity to create more effects with a closure
        command_spawn_and(
            (
                Spinny,
                Sprite::from_image(image_handle.clone()),
                Transform::from_scale(Vec3::splat(10.0)),
            ),
            |parent| {
                command_spawn((
                    ChildOf(parent), // This is where the relationship happens!
                    Spinny,
                    Sprite::from_image(image_handle),
                    Transform::from_xyz(20.0, 20.0, 0.0).with_scale(Vec3::splat(0.5)),
                ))
            },
        )
    })
}
fn main() { bevy::ecs::system::assert_is_system(spawn_relationship.pipe(affect)) }