generic_reflection/generic_reflection.rs
1//! Demonstrates how reflection is used with generic Rust types.
2
3use bevy::prelude::*;
4use std::any::TypeId;
5
6fn 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)]
18struct MyType<T> {
19 value: T,
20}
21
22fn 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}