bevyengine / bevyengine/bevy

Improve ergonomics when using parent/child relationships with component hooks

Open
#14,545 2 comments 0 reactions 0 assignees View on GitHub
A-ECS C-Usability
Dominant language
Rust
Stars
48.2k
Forks
4.8k
Avg merge
3d 22h
Merged PRs (30d)
161

Description

## 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?

- Manually setting via set_parent
- This is a good workaround, but not obvious when or why it should be used over child builder, and is prone to errors
- Adding a specific system to track `Added` components instead of using `on_add`
- This is a more robust method, but it separates code into two orthogonal boxes. I keep components in a separate module from systems and plugins, so this would mean I'd have logic that does roughly the same thing in two very different places in my codebase, which isn't great ergonomically.

----

Additional information:

[Original discussion post](https://github.com/bevyengine/bevy/discussions/14506)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.