examples/systems/
system_mutate_entity.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4
5#[derive(Component)]
6struct Timeout {
7    pub value: f32,
8}
9
10fn main() {
11    let world = World::new();
12
13    // System that deletes an entity after a timeout expires
14    world
15        .system::<&mut Timeout>()
16        .each_iter(|it, index, timeout| {
17            timeout.value -= it.delta_time();
18            if timeout.value <= 0.0 {
19                // Delete the entity
20
21                // To make sure that the storage doesn't change while a system
22                // is iterating entities, and multiple threads can safely access
23                // the data, mutations (like a delete) are added to a command
24                // queue and executed when it's safe to do so.
25
26                // When the entity to be mutated is not the same as the entity
27                // provided by the system, an additional mut() call is required.
28                // See the mutate_entity_handle example.
29                let e = it.entity(index);
30                e.destruct();
31                println!("Expire: {} deleted!", e.name());
32            }
33        });
34
35    // System that prints remaining expiry time
36    world.system::<&Timeout>().each_entity(|e, timeout| {
37        println!(
38            "PrintExpire: {} has {:.2} seconds left",
39            e.name(),
40            timeout.value
41        );
42    });
43
44    // Observer that triggers when entity is actually deleted
45    world
46        .observer::<flecs::OnRemove, &Timeout>()
47        .each_entity(|e, _timeout| {
48            println!("Expired: {} actually deleted", e.name());
49        });
50
51    let e = world.entity_named("MyEntity").set(Timeout { value: 2.5 });
52
53    world.set_target_fps(1.0);
54
55    while world.progress() {
56        // If entity is no longer alive, exit
57        if !e.is_alive() {
58            break;
59        }
60
61        println!("Tick...");
62    }
63
64    // Output:
65    //  PrintExpire: MyEntity has 2.00 seconds left
66    //  Tick...
67    //  PrintExpire: MyEntity has 0.99 seconds left
68    //  Tick...
69    //  Expire: MyEntity deleted!
70    //  PrintExpire: MyEntity has -0.03 seconds left
71    //  Expired: MyEntity actually deleted
72}
73
74#[cfg(feature = "flecs_nightly_tests")]
75#[test]
76fn test() {
77    let output_capture = OutputCapture::capture().unwrap();
78    main();
79    assert!(output_capture.output_string().contains("deleted"));
80}