component_group icon indicating copy to clipboard operation
component_group copied to clipboard

Nested ComponentGroups

Open sunjay opened this issue 7 years ago • 0 comments

Let's say you have a player group that looks like this:

#[derive(ComponentGroup)]
struct PlayerComponents {
    player: Player, // marker component
    position: Position,
    health: Health,
    animation: Option<Animation>,
}

The Player marker component is important to have, but will never be modified. Copying it over and over again when doing updates is kind of wasteful. One way to potentially solve this is by having two separate groups:

// Need to be added once, then never updated
#[derive(ComponentGroup)]
struct StaticPlayerComponents {
    player: Player, // marker component
    // etc. (could be many more, e.g. UserId, OutfitColor, ...)
}

// This can be used to quickly move the components that we know can change
#[derive(ComponentGroup)]
struct DynamicPlayerComponents {
    position: Position,
    health: Health,
    animation: Option<Animation>,
}

Then you can call create once and then call update to add the static and dynmaic components to an entity. This is not a great API though because you need to remember to do both operations. More importantly, it never actually makes sense to add StaticPlayerComponents without DynamicPlayerComponents.

It would be neat if something like this could work instead:

#[derive(ComponentGroup)]
struct PlayerComponents {
    player: Player, // marker component
    // etc. (could be many more, e.g. UserId, OutfitColor, ...)

    // Need #[group] annotation because macros don't know the types of fields
    #[group] dynamic_components: DynamicPlayerComponents,
}

This no longer requires that you remember to add both groups to the same entity and everything can be done in one call again.

You can update just the dynamic components by using DynamicPlayerComponents.

sunjay avatar Dec 23 '18 05:12 sunjay