Component

Derive Macro Component 

Source
#[derive(Component)]
{
    // Attributes available to this derive:
    #[component]
    #[require]
    #[relationship]
    #[relationship_target]
    #[entities]
}
Expand description

Cheat sheet for derive syntax, see full explanation and examples on the Component trait doc.

§Immutability

#[derive(Component)]
#[component(immutable)]
struct MyComponent;

§Sparse instead of table-based storage

#[derive(Component)]
#[component(storage = "SparseSet")]
struct MyComponent;

§Required Components

#[derive(Component)]
#[require(
    // `Default::default()`
    A,
    // tuple structs
    B(1),
    // named-field structs
    C {
        x: 1,
        ..default()
    },
    // unit structs/variants
    D::One,
    // associated consts
    E::ONE,
    // constructors
    F::new(1),
    // arbitrary expressions
    G = make(1, 2, 3)
)]
struct MyComponent;

§Relationships

#[derive(Component)]
#[relationship(relationship_target = Children)]
pub struct ChildOf {
    // Marking the field is not necessary if there is only one.
    #[relationship]
    pub parent: Entity,
    internal: u8,
};

#[derive(Component)]
#[relationship_target(relationship = ChildOf)]
pub struct Children(Vec<Entity>);

On despawn, also despawn all related entities:

#[derive(Component)]
#[relationship_target(relationship_target = Children, linked_spawn)]
pub struct Children(Vec<Entity>);

§Hooks

#[derive(Component)]
#[component(hook_name = function)]
struct MyComponent;

where hook_name is on_add, on_insert, on_replace or on_remove;
function can be either a path, e.g. some_function::<Self>, or a function call that returns a function that can be turned into a ComponentHook, e.g. get_closure("Hi!").

§Ignore this component when cloning an entity

#[derive(Component)]
#[component(clone_behavior = Ignore)]
struct MyComponent;