Skip to main content

examples/relationships/
relationships_exclusive.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4// Type for Platoon relationship
5#[derive(Component)]
6struct Platoon;
7
8fn main() {
9    let world = World::new();
10
11    // Register Platoon as exclusive relationship. This ensures that an entity
12    // can only belong to a single Platoon.
13    world.component::<Platoon>().add(flecs::Exclusive);
14
15    // Create two platoons
16    let platoon_1 = world.entity();
17    let platoon_2 = world.entity();
18
19    // Create a unit
20    let unit = world.entity();
21
22    // Add unit to platoon 1
23    unit.add((Platoon, platoon_1));
24
25    // Log platoon of unit
26    println!("Unit in platoon 1: {}", unit.has((Platoon, platoon_1))); // true
27    println!("Unit in platoon 2: {}", unit.has((Platoon, platoon_2))); // false
28
29    println!();
30
31    // Add unit to platoon 2. Because Platoon is an exclusive relationship, this
32    // both removes (Platoon, platoon_1) and adds (Platoon, platoon_2) in a
33    // single operation.
34    unit.add((Platoon, platoon_2));
35
36    // Log platoon of unit
37    println!("Unit in platoon 1: {}", unit.has((Platoon, platoon_1))); // false
38    println!("Unit in platoon 2: {}", unit.has((Platoon, platoon_2))); // true
39
40    // Output:
41    //  Unit in platoon 1: true
42    //  Unit in platoon 2: false
43    //
44    //  Unit in platoon 1: false
45    //  Unit in platoon 2: true
46}
47
48#[cfg(feature = "flecs_nightly_tests")]
49#[test]
50fn test() {
51    let output_capture = OutputCapture::capture().unwrap();
52    main();
53    output_capture.test("relationships_exclusive".to_string());
54}