Skip to main content

examples/entities/
component_attributes.rs

1use crate::z_ignore_test_common::*;
2use flecs_ecs::prelude::*;
3
4// not meant to make sense on why these attributes are added
5// just for demonstration purposes
6#[derive(Debug, Component)]
7#[flecs(
8    name = "Position",
9    meta,
10    // component traits
11    traits(Sparse, (With, WorldPosition)),
12    // adding components
13    add((Eats, Apples)),
14    // setting components
15    set((Likes { score: 10 }, Bob)),
16    // hooks
17    hooks(
18        on_add(|e, _| { println!("added Position to {}", e.name()); }),
19        on_set(|e, p: &mut Position| { println!("set {:?} for {}", p, e.name()); }),
20        on_remove(|e, p: &mut Position| { println!("removed {:?} from {}", p, e.name()); })
21    )
22)]
23pub struct Position {
24    pub x: f32,
25    pub y: f32,
26}
27
28#[derive(Component, Default)]
29pub struct WorldPosition;
30
31#[derive(Component)]
32pub struct Eats;
33
34#[derive(Component)]
35pub struct Apples;
36
37#[derive(Debug, Component)]
38pub struct Likes {
39    pub score: i32,
40}
41
42#[derive(Component)]
43pub struct Bob;
44
45#[test]
46fn main() {
47    let world = World::new();
48
49    let e = world.entity_named("Bob");
50    e.set(Position { x: 1.0, y: 2.0 });
51    e.remove(Position::id());
52
53    // Output
54    // added Position to Bob
55    // set Position { x: 1.0, y: 2.0 } for Bob
56    // removed Position { x: 1.0, y: 2.0 } from Bob
57}
58
59#[cfg(feature = "flecs_nightly_tests")]
60#[test]
61fn test() {
62    let output_capture = OutputCapture::capture().unwrap();
63    main();
64    output_capture.test("component_attributes".to_string());
65}