Skip to main content

examples/observers/
observer_basics.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
11fn main() {
12    let world = World::new();
13
14    world
15        .observer::<flecs::OnAdd, ()>()
16        .with(Position::id())
17        .each_iter(|it, index, _| {
18            // We use .with(Position::id()) because we cannot safely access the component
19            // value here. The component value is uninitialized when the OnAdd event
20            // is emitted, which is UB in Rust. To work around this, we use .with::<T>
21            println!(" - OnAdd: {}: {}", it.event_id().to_str(), it.entity(index));
22        });
23
24    // Create an observer for three events
25    world
26        .observer::<flecs::OnSet, &Position>()
27        .add_event(flecs::OnRemove)
28        .each_iter(|it, index, pos| {
29            println!(
30                " - {}: {}: {}: with {:?}",
31                it.event().name(),
32                it.event_id().to_str(),
33                it.entity(index),
34                pos
35            );
36        });
37
38    // Create entity, set Position (emits EcsOnAdd and EcsOnSet)
39    let entity = world.entity_named("e1").set(Position { x: 10.0, y: 20.0 });
40
41    // Remove Position (emits EcsOnRemove)
42    entity.remove(Position::id());
43
44    // Remove Position again (no event emitted)
45    entity.remove(Position::id());
46
47    // Output:
48    //  - OnAdd: Position: e1
49    //  - OnSet: Position: e1: with Position { x: 10.0, y: 20.0 }
50    //  - OnRemove: Position: e1: with Position { x: 10.0, y: 20.0 }
51}
52
53#[cfg(feature = "flecs_nightly_tests")]
54#[test]
55fn test() {
56    let output_capture = OutputCapture::capture().unwrap();
57    main();
58    output_capture.test("observer_basics".to_string());
59}