Skip to content

Instantly share code, notes, and snippets.

@thebluefish
Last active March 31, 2024 01:49
Show Gist options
  • Save thebluefish/c2be86f10274245e20932d8325457747 to your computer and use it in GitHub Desktop.
Save thebluefish/c2be86f10274245e20932d8325457747 to your computer and use it in GitHub Desktop.
use bevy::prelude::*;
use bevy::reflect::{GetTypeRegistration, ReflectMut, Typed, TypeInfo};
fn main() {
let mut app = App::new();
app
.add_plugins(MinimalPlugins)
.register_type_data::<String, ReflectFoo>()
.register_type_data::<usize, ReflectFoo>()
.register_type_data::<bool, ReflectFoo>()
;
let registry = app.world.resource::<AppTypeRegistry>().read();
let registration = APointClass::get_type_registration();
let reflect_default = registration.data::<ReflectDefault>().unwrap();
let mut default_value = reflect_default.default();
println!("Default Value: {:?}", default_value);
let ReflectMut::Struct(mut_value) = default_value.reflect_mut() else { unreachable!() };
let TypeInfo::Struct(info) = APointClass::type_info() else { unreachable!() };
for named_field in info.iter() {
let name = named_field.name();
let field_type_id = named_field.type_id();
let field_registry = registry.get(field_type_id).unwrap();
let property = field_registry.data::<ReflectFoo>().unwrap();
let property = property.get(mut_value.field(name).unwrap()).unwrap();
println!("Property: {}", property.doubled());
}
}
#[derive(Component, Reflect)]
#[reflect(Component, Default)]
struct APointClass {
test_string: String,
test_usize: usize,
test_bool: bool,
}
impl Default for APointClass {
fn default() -> Self {
Self {
test_string: "HELLO WORLD!".to_string(),
test_usize: 69,
test_bool: true,
}
}
}
#[reflect_trait]
pub trait Foo: Reflect {
fn doubled(&self) -> String;
}
impl Foo for String {
fn doubled(&self) -> String {
format!("{self}{self}")
}
}
impl Foo for usize {
fn doubled(&self) -> String {
format!("{}", self * 2)
}
}
impl Foo for bool {
fn doubled(&self) -> String {
format!("{}", !self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment