Skip to main content

examples/entities/
entity_hooks.rs

1use 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(Component)]
12pub struct Tag;
13
14fn main() {
15    let world = World::new();
16
17    world
18        .component::<Position>()
19        .on_add(|entity, _pos| {
20            println!("added Position to {:?}", entity.name());
21        })
22        .on_remove(|entity, pos| {
23            println!("removed {:?} from {:?}", pos, entity.name());
24        })
25        .on_set(|entity, pos| {
26            println!("set {:?} for {:?}", pos, entity.name());
27        });
28
29    let entity = world.entity_named("Bob");
30
31    entity.set(Position { x: 10.0, y: 20.0 });
32
33    // This operation changes the entity's archetype, which invokes a move
34    // add is used for adding tags.
35    entity.add(Tag);
36
37    entity.destruct();
38
39    // Output:
40    //  added Position { x: 0.0, y: 0.0 } to "Bob"
41    //  set Position { x: 10.0, y: 20.0 } for "Bob"
42    //  removed Position { x: 10.0, y: 20.0 } from "Bob"
43}
44
45#[cfg(feature = "flecs_nightly_tests")]
46#[test]
47fn test() {
48    let output_capture = OutputCapture::capture().unwrap();
49    main();
50    output_capture.test("entity_hooks".to_string());
51}