Skip to main content

examples/prefabs/
prefab_typed.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4// Just like how entities can be associated with a type (like components)
5// prefabs can be associated with types as well. Types can be more convenient to
6// work with than entity handles, for a few reasons:
7//
8// - There is no need to pass around or store entity handles
9// - Prefabs automatically assume the name of the type
10// - Nested types can be used to create prefab hierarchies
11//
12// While this functionality is not unique to prefabs (the same mechanism is
13// used to distribute component handles), prefabs are a good fit, especially
14// when combined with prefab slots (see slots example and code below).
15
16// Create types that mirror the prefab hierarchy.
17#[derive(Component)]
18struct Base;
19#[derive(Component)]
20struct Head;
21
22#[derive(Component)]
23struct Turret;
24
25#[derive(Component)]
26struct Beam;
27#[derive(Component)]
28struct Railgun;
29
30fn main() {
31    let world = World::new();
32
33    // Associate types with prefabs
34    world.prefab_type::<Turret>();
35
36    world.prefab_type::<Base>().child_of(Turret).slot_of(Turret);
37
38    world.prefab_type::<Head>().child_of(Turret).slot_of(Turret);
39
40    world.prefab_type::<Railgun>().is_a(Turret);
41    world
42        .prefab_type::<Beam>()
43        .slot_of(Railgun)
44        .child_of(Railgun);
45
46    // Create prefab instance.
47    let inst = world.entity_named("my_railgun").is_a(Railgun);
48
49    // Get entities for slots
50    let inst_base = inst.target(Base, 0).unwrap();
51    let inst_head = inst.target(Head, 0).unwrap();
52    let inst_beam = inst.target(Beam, 0).unwrap();
53
54    println!("instance base: {}", inst_base.path().unwrap());
55    println!("instance head: {}", inst_head.path().unwrap());
56    println!("instance beam: {}", inst_beam.path().unwrap());
57
58    // Output:
59    //  instance base: ::my_railgun::Base
60    //  instance head: ::my_railgun::Head
61    //  instance beam: ::my_railgun::Beam
62}
63
64#[cfg(feature = "flecs_nightly_tests")]
65#[test]
66fn test() {
67    let output_capture = OutputCapture::capture().unwrap();
68    main();
69    output_capture.test("prefab_typed".to_string());
70}