bevyengine / bevy

A refreshingly simple data-driven game engine built in Rust
https://bevyengine.org
Apache License 2.0
36.25k stars 3.58k forks source link

Use `OnAdd` hooks to verify that state-scoped entities are only spawned during the correct state #15100

Open alice-i-cecile opened 2 months ago

alice-i-cecile commented 2 months ago

Another thing, we can add an OnAdd hook to StateScoped that will check the state and remove the entity if it's incorrect. This compliments the existing on-exit behavior by doing on-spawn validation.

Originally posted by @MiniaczQ in https://github.com/bevyengine/bevy/issues/15072#issuecomment-2336693883

UkoeHB commented 2 months ago

If we consider that practically all game entities will have StateScoped, this would introduce a fixed global cost to spawning entities (or at least the root entities of hierarchies). What is the perf comparison between an OnAdd hook and e.g. a system that polls for Added (not that I'm recommending to use such a system, but we have a number of those in the bevy codebase)?

alice-i-cecile commented 2 months ago

OnAdd hooks will be paid once on entity spawning, and only for those entities which have the state scoped component. Added filters will be paid every frame, scaling linearly with the number of matching entities.

I'd love to see real numbers though.

MiniaczQ commented 2 months ago

I don't believe that's the correct complementary behavior. The current behavior is "despawn on exit", so its complement would be "spawn on enter", which would be genuinely useful but is blocked on the better scenes work. As another example, "show on enter" + "hide on exit" is already possible.

From @benfrankel in #15072