Events that store a Component trait object #3221
-
I wanted to make an event which could store a boxed trait object, where the trait required the /// Trait for implementable actions
trait Ability: Component {}
/// Event type that stores the action that is currently being executed
struct QueuedAbility {
ability: Box<dyn Ability>,
} Looks good, but the compiler is complaining to me that
What the heck should I set that associated type to? Let's look at how to solve it. (Already solved thanks to help on Discord, but written up here for Google and confused users). |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The trick is that you need to set the associated type to a type that implements /// Trait for implementable actions
trait Ability: Component<Storage = SparseStorage> {}
/// Event type that stores the action that is currently being executed
struct QueuedAbility {
// Storage is the associated type of the Component trait
// Here, we're setting it to be the standard enum type
ability: Box<dyn Ability<Storage = SparseStorage>>,
}
impl QueuedAbility {
fn new(ability: impl Ability) -> Self {
QueuedAbility {
ability: Box::new(ability),
}
}
}
#[derive(Component)]
// TableStorage is the default
#[component(storage = "SparseSet")]
struct Dash;
impl Ability for Dash {} There's one minor limitation: all of the components must have the same storage type. You could probably get around this with an P.S. Specifying |
Beta Was this translation helpful? Give feedback.
The trick is that you need to set the associated type to a type that implements
ComponentStorage
: currentlySparseStorage
orTableStorage
.