docs/bevy/examples/reflection/generic_reflection.rs 957 B · 33 lines · raw · history

1 //! Demonstrates how reflection is used with generic Rust types.
2
3 use bevy::prelude::*;
4 use std::any::TypeId;
5
6 fn main() {
7 App::new()
8 .add_plugins(DefaultPlugins)
9 // You must manually register each instance of a generic type
10 .register_type::<MyType<u32>>()
11 .add_systems(Startup, setup)
12 .run();
13 }
14
15 /// The `#[derive(Reflect)]` macro will automatically add any required bounds to `T`,
16 /// such as `Reflect` and `GetTypeRegistration`.
17 #[derive(Reflect)]
18 struct MyType<T> {
19 value: T,
20 }
21
22 fn setup(type_registry: Res<AppTypeRegistry>) {
23 let type_registry = type_registry.read();
24
25 let registration = type_registry.get(TypeId::of::<MyType<u32>>()).unwrap();
26 info!(
27 "Registration for {} exists",
28 registration.type_info().type_path(),
29 );
30
31 // MyType<String> was not manually registered, so it does not exist
32 assert!(type_registry.get(TypeId::of::<MyType<String>>()).is_none());
33 }