Skip to content
Flecs v4.1
prefabs/typed_prefabs

  • C++

    View on GitHub

    1#include <typed_prefabs.h>
    2#include <iostream>
    3
    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 hierarchies.
    15
    16// Create types that mirror the prefab hierarchy.
    17struct Turret {
    18 struct Base {};
    19 struct Head {};
    20};
    21
    22struct Railgun {
    23 struct Beam {};
    24};
    25
    26int main() {
    27 flecs::world ecs;
    28
    29 // Associate types with prefabs
    30 ecs.prefab<Turret>();
    31 ecs.prefab<Turret::Base>();
    32 ecs.prefab<Turret::Head>();
    33
    34 ecs.prefab<Railgun>().is_a<Turret>();
    35 ecs.prefab<Railgun::Beam>();
    36
    37 // Create prefab instance.
    38 flecs::entity inst = ecs.entity("my_railgun").is_a<Railgun>();
    39
    40 // Get instantiated children by name
    41 flecs::entity inst_base = inst.lookup("Base");
    42 flecs::entity inst_head = inst.lookup("Head");
    43 flecs::entity inst_beam = inst.lookup("Beam");
    44
    45 std::cout << "instance base: " << inst_base.path() << "\n";
    46 std::cout << "instance head: " << inst_head.path() << "\n";
    47 std::cout << "instance beam: " << inst_beam.path() << "\n";
    48
    49 // Output:
    50 // instance base: ::my_railgun::Base
    51 // instance head: ::my_railgun::Head
    52 // instance beam: ::my_railgun::Beam
    53}
    flecs::entity entity(Args &&... args) const
    Create an entity.
    Definition impl.hpp:195
    flecs::entity prefab(const char *name=nullptr) const
    Create a prefab that's associated with a type.
    Definition impl.hpp:18
    const Self & is_a(entity_t second) const
    Shortcut for add(IsA, entity).
    Definition builder.hpp:122
    flecs::string path(const char *sep="::", const char *init_sep="::") const
    Return the entity path.
    flecs::entity lookup(const char *path, bool search_path=false) const
    Lookup an entity by name.
    Definition impl.hpp:177
    Entity.
    Definition entity.hpp:30
    The world.
    Definition world.hpp:129