Skip to content

Make StateTransitionSteps public for better ergonomics of State Scoped Resources #16594

@Phoqinu

Description

@Phoqinu

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

As of 0.15 Entitys and Events can be bound to a state.
Entities will be despawned on state exit and events will be initialized and cleaned-up on state exit.
There's no official way of doing this for resources but we can make our own.

Consider this naive impl:

fn init_state_scoped_resource<R: Resource + FromWorld>(
        &mut self,
        state: impl States,
    ) -> &mut Self {
        self.add_systems(OnEnter(state.clone()), init_state_scoped_resource_impl::<_, R>(state.clone()));
        self.add_systems(OnExit(state.clone()), clear_state_scoped_resource_impl::<_, R>(state));
        self
}
app.init_state_scoped_resource::<Foo>(BazState::Bar);

While it does work it can race with this system:

app.add_systems(OnEnter(BazState::Bar), |foo: Res<Foo>| {});

What solution would you like?

There are 3 solutions I can think of:

  1. Keep using naive OnEnter/OnExit and offer some SystemSet to let users (me) order racy systems but this is imo quite un-ergonomic and error prone - you can forget to do it.
  2. Switch OnEnter/OnExit schedules to StateTransition schedule and modify inner init/clear fns to behave like clear_state_scoped_entities. This fixes possible race and there's no need to offer system set but it will behave differently than other systems running in that schedule and I'm not sure what effects it could have.
  3. Like 2. + add .in_set(StateTransitionSteps::EnterSchedules) and .in_set(StateTransitionSteps::ExitSchedules) to user-defined init_state_scoped_resource inner fns. This will offer the "best" compatibility out of the mentioned 3 but it's not possible because StateTransitionSteps is private.

What alternative(s) have you considered?

I can't think of other alternatives.

Additional context

None.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-StatesApp-level states machinesC-UsabilityA targeted quality-of-life change that makes Bevy easier to useD-TrivialNice and easy! A great choice to get started with BevyS-Ready-For-ImplementationThis issue is ready for an implementation PR. Go for it!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions