bevyengine / bevy

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

Improve ergonomics when using parent/child relationships with component hooks #14545

Open piedoom opened 3 months ago

piedoom commented 3 months ago

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

When using component hooks, it is possible to access the Entity Parent on_remove but not on_add or on_insert, specifically when using a child builder. It would be ideal to always have access to the Parent in any hook while using the child builder.

This is somewhat unexpected behavior from the perspective of someone learning hooks, as it is unclear why one state functions while the does not. Furthermore, it is possible to work around the child builder problem by manually setting a parent with set_parent, however this is discouraged by Bevy's docs in favor of the child builder, and it is still opaque as to why one method works without understanding a bit about how Bevy's parent/child hierachy works.

Concrete use-case

In my game, I have a parent Entity that has an inventory. When inventory items are equipped, they are spawned as children onto the parent entity. I like this approach because it feels idiomatic with an ECS, but it does require extra internal state tracking for the inventory. For instance, the inventory has a maximum size. Instead of calculating the size every frame, it's nice to track the space used as a separate variable, and update it whenever I add or remove an equip. This seems like an ideal use for hooks, but I need to be able to access the parent entity. Note the hierarchy is required so I can add multiple items of the same type of component, e.g. two weapons can be equipped at once.

What solution would you like?

I am unsure as to the technical implementation, but ideally I could use a child builder as normal and access the Parent entity in any hook.

What alternative(s) have you considered?


Additional information:

Original discussion post

alice-i-cecile commented 3 months ago

Related to #12235, but distinct.