Created
March 14, 2025 22:41
-
-
Save RJ/1b4de41c6b116a3c2c1e938ee11cbbc6 to your computer and use it in GitHub Desktop.
bevy ReflectEvent example for reflected triggers / observers / events / reflection.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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