examples/prefabs/
prefab_hierarchy.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4// When a prefab has children, they are instantiated for an instance when the
5// IsA relationship to the prefab is added.
6
7fn main() {
8    let world = World::new();
9
10    // Create a prefab hierarchy.
11    let spaceship = world.prefab_named("SpaceShip");
12    world.prefab_named("Engine").child_of_id(spaceship);
13    world.prefab_named("Cockpit").child_of_id(spaceship);
14
15    // Instantiate the prefab. This also creates an Engine and Cockpit child
16    // for the instance.
17    let inst = world.entity_named("my_spaceship").is_a_id(spaceship);
18
19    // Because of the IsA relationship, the instance now has the Engine and Cockpit
20    // children of the prefab. This means that the instance can look up the Engine
21    // and Cockpit entities.
22    if let Some(inst_engine) = inst.try_lookup_recursive("Engine") {
23        if let Some(inst_cockpit) = inst.try_lookup_recursive("Cockpit") {
24            println!("instance engine:  {:?}", inst_engine.path().unwrap());
25            println!("instance cockpit: {:?}", inst_cockpit.path().unwrap());
26        } else {
27            println!("entity lookup failed");
28        }
29    }
30
31    // Output:
32    //  instance engine:  "::my_spaceship::Engine"
33    //  instance cockpit: "::my_spaceship::Cockpit"
34}
35
36#[cfg(feature = "flecs_nightly_tests")]
37#[test]
38fn test() {
39    let output_capture = OutputCapture::capture().unwrap();
40    main();
41    output_capture.test("prefab_hierarchy".to_string());
42}