examples/entities/
entity_iterate_components.rs1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4
5#[derive(Debug, Component)]
6pub struct Position {
7 pub x: f32,
8 pub y: f32,
9}
10
11#[derive(Debug, Component)]
12pub struct Velocity {
13 pub x: f32,
14 pub y: f32,
15}
16
17#[derive(Component)]
18pub struct Eats;
19
20#[derive(Component)]
21pub struct Apples;
22
23#[derive(Component)]
24pub struct Human;
25
26fn iterate_components(entity: EntityView) {
27 println!("[{:?}]", entity.archetype());
29 println!();
30 let mut count_components = 0;
32 entity.each_component(|id| {
33 println!("{}: {}", count_components, id.to_str());
34 count_components += 1;
35 });
36 println!();
37
38 count_components = 0;
42
43 entity.each_component(|id| {
44 let mut string: String = String::new();
45 string.push_str(format!("{count_components}: ").as_str());
46
47 count_components += 1;
48 if id.is_pair() {
49 let rel = id.first_id();
51 let target = id.second_id();
52 string.push_str(format!("rel: {}, target: {}", rel.name(), target.name()).as_str());
53 } else {
54 let comp = id.entity_view();
56 string.push_str(format!("entity: {}", comp.name()).as_str());
57 }
58
59 println!("{string}");
60 });
61}
62
63fn main() {
64 let world = World::new();
65
66 let bob = world
67 .entity_named("Bob")
68 .set(Position { x: 10.0, y: 20.0 })
69 .set(Velocity { x: 1.0, y: 1.0 })
70 .add(Human)
71 .add((Eats, Apples));
72
73 println!("Bob's components:");
74 iterate_components(bob);
75
76 println!();
77
78 println!("Position's components:");
80 iterate_components(world.component::<Position>().entity());
81
82 }
111
112#[cfg(feature = "flecs_nightly_tests")]
113#[test]
114fn test() {
115 let output_capture = OutputCapture::capture().unwrap();
116 main();
117 output_capture.test("entity_iterate_components".to_string());
118}