Seldom-SE / seldom_state

Component-based state machine plugin for Bevy. Useful for AI, player state, and other entities that occupy different states.
Apache License 2.0
172 stars 18 forks source link

Access to a state in `on_enter`, and maybe `on_exit` #12

Open soanvig opened 1 week ago

soanvig commented 1 week ago

This is actually self-descriptive.

I need to perform some behavior (insert a component) that depends on the state I'm inserting. If I have no access to the state, then I cannot effectively perform any logic inside on_enter.

I can help on PR.

Seldom-SE commented 1 week ago

This seems reasonable API-wise, but I may significantly change some of the APIs in Bevy 0.14 (because of observers). So I'll get back to this.

For now, you can use the Added filter in a system, or an odd workaround like this:

commands.spawn((
    SomeInitialState,
    StateMachine::default()
        .on_enter::<MyState>(|entity_cmds| entity_cmds.add(|entity: Entity, world: &mut World| {
            if world.get::<MyState>(entity).unwrap().should_also_be_fancy {
                world.entity_mut(entity).insert(Fancy);
            }
        })),
));
soanvig commented 1 week ago

I actually did use .command_on_enter as I have only one entity with a given state at the moment, so I can just query it. But thanks for the idea.

Looking forward 0.14 and observers