#DynamicStruct -> Concrete type

29 messages · Page 1 of 1 (latest)

autumn sentinel
#

I'm trying to get get the trait of a type. but it's a DynamicStruct(pgc::powerups::projectiles::poisenous::PoisenousProjectiles)

so my current code is this:

let reflect = component.0.as_ref(); // DynamicStruct
let represented_info = reflect.get_represented_type_info().unwrap();
let reflect_powerup_descriptor = type_registry
    .get_type_data::<ReflectPowerupDescriptor>(
        represented_info.type_id(),
    )
    .unwrap(); // Works!

let powerup_descriptor = reflect_powerup_descriptor.get(reflect).unwrap(); // Crashes!
println!("Powerup: {:?}", powerup_descriptor.describe());

so what i think the problem is, is that reflect is still the dynamic type, and not the actual one, so it of course doesn't implement PowerupDescriptor... so how can i correctly get the trait then?

robust bear
#

You’ll need to convert reflect to a concrete instance using FromReflect

#

This can be done dynamically by using its ReflectFromReflect type data from the registry

autumn sentinel
#

but i don't...

robust bear
#

For FromReflect you would

#

ReflectFromReflect is completely dynamic

autumn sentinel
#

ah sorry, missed that part

robust bear
#

Or rather, it stores the FromReflect method for a given type. So pulling that type from the registry will give you the correct ReflectFromReflect instance

robust bear
autumn sentinel
#

hm okay, one thing i don't understand

#
let registration = registry.get_with_type_path(<Foo as TypePath>::type_path()).unwrap();
#

thats how it's done on the example

#

how do i get my registration... without knowing the type?

#

ah

robust bear
#

You can do it the same way you do to get ReflectPowerupDescriptor

autumn sentinel
#
let registration = type_registry.get_with_type_path(reflect.reflect_type_path()).unwrap();
robust bear
#

Yes but there’s one gotcha

#

That’ll return the type path for the dynamic type

autumn sentinel
#

aw :(

robust bear
#

You want to go through the represented type info

autumn sentinel
#

ah

#

ye i forgor

#
let registration = type_registry
    .get_with_type_path(
        reflect.get_represented_type_info().unwrap().type_path(),
    )
    .unwrap();
robust bear
#

Yeah that should work

autumn sentinel
#
let reflect = component.0.as_ref();
let registration = type_registry
    .get_with_type_path(
        reflect.get_represented_type_info().unwrap().type_path(),
    )
    .unwrap();
let rfr = registration.data::<ReflectFromReflect>().unwrap();
let concrete = rfr.from_reflect(reflect).unwrap();

let reflect_powerup_descriptor =
    registration.data::<ReflectPowerupDescriptor>().unwrap();

let powerup_descriptor = reflect_powerup_descriptor
    .get(concrete.as_reflect())
    .unwrap();
println!("Powerup: {:?}", powerup_descriptor.describe());

final code snippet

#

thanks a lot!