Skip to content

Instantly share code, notes, and snippets.

@RJ
Created March 14, 2025 22:41
Show Gist options
  • Save RJ/1b4de41c6b116a3c2c1e938ee11cbbc6 to your computer and use it in GitHub Desktop.
Save RJ/1b4de41c6b116a3c2c1e938ee11cbbc6 to your computer and use it in GitHub Desktop.
bevy ReflectEvent example for reflected triggers / observers / events / reflection.
/// A struct used to operate on reflected [`Event`] of a type.
///
/// A [`ReflectEvent`] for type `T` can be obtained via
/// [`bevy::reflect::TypeRegistration::data`].
#[derive(Clone)]
pub struct ReflectEvent(ReflectEventFns);
/// The raw function pointers needed to make up a [`ReflectEvent`].
///
/// This is used when creating custom implementations of [`ReflectEvent`] with
/// [`ReflectEvent::new()`].
#[derive(Clone)]
pub struct ReflectEventFns {
/// Function pointer implementing [`ReflectEvent::send()`].
pub send: fn(&dyn Reflect, &mut World),
}
impl ReflectEventFns {
/// Get the default set of [`ReflectEventFns`] for a specific component type using its
/// [`FromType`] implementation.
///
/// This is useful if you want to start with the default implementation before overriding some
/// of the functions to create a custom implementation.
pub fn new<T: Event + Reflect + Clone>() -> Self {
<ReflectEvent as FromType<T>>::from_type().0
}
}
impl ReflectEvent {
/// Sends reflected [`Event`] to world using [`send()`](ReflectEvent::send).
pub fn send(&self, event: &dyn Reflect, world: &mut World) {
(self.0.send)(event, world)
}
/// Create a custom implementation of [`ReflectEvent`].
pub fn new(fns: ReflectEventFns) -> Self {
Self(fns)
}
/// The underlying function pointers implementing methods on `ReflectEvent`.
pub fn fn_pointers(&self) -> &ReflectEventFns {
&self.0
}
}
impl<E: Event + Reflect + Clone> FromType<E> for ReflectEvent {
fn from_type() -> Self {
ReflectEvent(ReflectEventFns {
send: |event, world| {
if let Some(ev) = event.downcast_ref::<E>() {
world.send_event(ev.clone());
}
},
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment