bevy/crates/bevy_ecs/hecs/examples/format.rs

40 lines
1.1 KiB
Rust
Raw Normal View History

2020-07-10 08:37:06 +00:00
// modified by Bevy contributors
2020-07-10 04:18:35 +00:00
//! One way to the contents of an entity, as you might do for debugging. A similar pattern could
//! also be useful for serialization, or other row-oriented generic operations.
2020-08-10 00:58:56 +00:00
fn format_entity(entity: bevy_hecs::EntityRef<'_>) -> String {
2020-08-16 03:27:41 +00:00
fn fmt<T: bevy_hecs::Component + std::fmt::Display>(
entity: bevy_hecs::EntityRef<'_>,
) -> Option<String> {
2020-07-10 04:18:35 +00:00
Some(entity.get::<T>()?.to_string())
}
2020-08-10 00:58:56 +00:00
const FUNCTIONS: &[&dyn Fn(bevy_hecs::EntityRef<'_>) -> Option<String>] =
2020-07-10 04:18:35 +00:00
&[&fmt::<i32>, &fmt::<bool>, &fmt::<f64>];
let mut out = String::new();
for f in FUNCTIONS {
if let Some(x) = f(entity) {
if out.is_empty() {
out.push_str("[");
} else {
out.push_str(", ");
}
out.push_str(&x);
}
}
if out.is_empty() {
out.push_str(&"[]");
} else {
out.push(']');
}
out
}
fn main() {
2020-08-10 00:58:56 +00:00
let mut world = bevy_hecs::World::new();
2020-07-10 04:18:35 +00:00
let e = world.spawn((42, true));
println!("{}", format_entity(world.entity(e).unwrap()));
}