Skip to content

AsEntity Trait #9367

@Zeenobit

Description

@Zeenobit

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

When working with Bevy, it is often desirable to store references to entities in types that represent those entities.
For example:

struct Parent(Entity);

struct Player {
    entity: Entity,
    ...
}

Currently, when trying to use these types for queries and other similar functions which take an Entity as input, the user must dereference this type as the entity:

let player_component = player_query.get(player.entity);

Often times, such as with the standard Parent(Entity) type, this syntax can be made less verbose by implement Deref<Target = Entity>:

let parent_component = parent_query.get(**parent);

Notice how this requires **, because usually the parent is given as a &Parent.

This can often create redundantly verbose code.
I propose that this alternative would be much cleaner and more readable:

let player_component = player_query.get(player);
let parent_component = parent_query.get(parent);

What solution would you like?

To solve this issue, we could introduce a new trait:

trait AsEntity {
   fn as_entity(&self) -> Entity;
}

Then we can implement this trait for types such as Entity, Parent, etc.
Additionally, the user can implement this trait for custom user data.

To make this work, all the top level functions that take entities as input would need to be refactored to take an impl AsEntity instead of Entity. If AsEntity is implemented for Entity, this should have no visible effect to the end user.
This would be functions like query.get() or world.entity().

What alternative(s) have you considered?

I'm not sure if a better name for this would be IntoEntity (considering how we have IntoSystem).
To me AsEntity makes more sense since we're usually trying to reference a thing "as an entity".

Additional context

N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ECSEntities, components, systems, and eventsC-FeatureA new feature, making something new possibleC-UsabilityA targeted quality-of-life change that makes Bevy easier to use

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions