Introduction
Prefabs are entities that can be used as templates for other entities. They can provide a convenient API for creating assets natively in the ECS. Prefabs have the following features:
- Prefab components can be shared across instances
- Inherited components can be overridden on a per-instance basis
- Inherited components can be auto-overridden on a per-prefab basis
- Prefab inheritance makes creating variations easy
- Prefabs can have children that are instantiated for instances
- Prefab children can be easily identified with prefab slots
- Prefabs are runtime accessible and modifiable
- Prefabs can be mapped to types for easy access in the C++ API
- Natively supported by Flecs Script & the JSON serializer
The following example shows how to instantiate a simple prefab:
-
C
.name = "SpaceShip",
});
ecs_set(ecs, SpaceShip, Defense, {50});
const Defense *d = ecs_get(world, inst_1, Defense);
ecs_id_t ecs_entity_t
An entity identifier.
#define ecs_entity(world,...)
Shorthand for creating an entity with ecs_entity_init().
#define ECS_COMPONENT(world, id)
Declare & define a component.
#define ecs_ids(...)
Convenience macro for creating compound literal id array.
-
C++
struct Defense {
float value;
};
.set(Defense{50});
const Defense *d = inst_1.
get<Defense>();
const T * get() const
Get component value.
-
C#
public record struct Defense(double Value);
Entity spaceship = world.Entity("Spaceship")
.Set(new Defense(50));
Entity inst1 = world.Entity().IsA(spaceship);
Entity inst2 = world.Entity().IsA(spaceship);
ref readonly Defense attack = ref inst1.Get<Defense>();
-
Rust
#[derive(Component)]
struct Defense {
value: u32,
}
// Create a spaceship prefab with a Defense component.
let spaceship = world.prefab_named("spaceship").set(Defense { value: 50 });
// Create two prefab instances
let inst_1 = world.entity().is_a_id(spaceship);
let inst_2 = world.entity().is_a_id(spaceship);
// Get instantiated component
inst_1.get::<&Defense>(|defense| {
println!("Defense value: {}", defense.value);
});
The following sections go over the different aspects of the prefab feature.
The Prefab tag
Prefabs are regular entities with as only difference that prefabs by default are not matched by queries. This allows prefab entities to coexist with regular entities in the same world without impacting game logic. The mechanism used to exclude prefabs from queries is a builtin Prefab
tag. The following example shows how to create a prefab:
-
C
void ecs_add_id(ecs_world_t *world, ecs_entity_t entity, ecs_id_t id)
Add a (component) id to an entity.
ecs_entity_t ecs_new(ecs_world_t *world)
Create new entity id.
-
C++
-
C#
Entity myPrefab = world.Prefab();
-
Rust
let myprefab = world.entity().add::<flecs::Prefab>();
// or the shortcut
let myprefab = world.prefab();
Queries don't match prefab entities unless the Prefab
tag is explicitly queried for. The following example shows how to match only prefabs by adding the Prefab
tag to a query:
-
C
.terms = {
}
});
FLECS_API const ecs_entity_t ecs_id(EcsDocDescription)
Component id for EcsDocDescription.
#define ecs_query(world,...)
Shorthand for creating a query with ecs_query_cache_init.
Queries are lists of constraints (terms) that match entities.
-
C++
world.query_builder<Position>()
.with(flecs::Prefab)
.build();
-
C#
world.QueryBuilder<Position>()
.With(Ecs.Prefab)
.Build();
-
Rust
// Only match prefab entities
world.query::<&Position>().with::<flecs::Prefab>().build();
Prefabs are only ignored by queries when they are matched on the $this
variable, which is the default for query terms. If a prefab component is matched through query traversal, a fixed term source or variable non-$this
source, the query will not ignore the prefab.
To match both regular and prefab entities, make the prefab term optional:
-
C
.terms = {
}
});
@ EcsOptional
The term may match.
-
C++
world.query_builder<Position>()
.with(flecs::Prefab).optional()
.build();
-
C#
world.QueryBuilder<Position>()
.With(Ecs.Prefab).Optional()
.Build();
-
Rust
// Only match prefab entities
world
.query::<&Position>()
.with::<flecs::Prefab>()
.optional()
.build();
Instead of an optional term, queries can also specify a MatchPrefabs
flag. This matches the same entities as an optional term, but since the term doesn't need to populate a field slightly improves performance:
-
C
.terms = {
},
});
#define EcsQueryMatchPrefab
Query must match prefabs.
-
C++
world.query_builder<Position>()
.build();
-
C#
world.QueryBuilder()
.QueryFlags(Ecs.QueryMatchPrefab)
.Build();
-
Rust
// Only match prefab entities
world
.query::<&Position>()
.query_flags(QueryFlags::MatchPrefab)
.build();
Component Inheritance
Entities can inherit components from prefabs. Inherited components are only stored once in memory, and shared across instances. This can be useful for static data that's shared across instances, such as material data, textures or meshes.
For a component to be inheritable, it needs to have the (OnInstantiate, Inherit)
trait (for more details see the ComponentTraits manual). The following example shows what happens when a prefab with one inheritable and one non-inheritable component is instantiated:
-
C
ecs_add_pair(world,
ecs_id(Defense),
.name = "SpaceShip",
});
ecs_set(ecs, SpaceShip, Defense, {50});
ecs_set(ecs, SpaceShip, Health, {100});
const Health *health = ecs_get(world, inst, Health);
const Defense *defense = ecs_get(world, inst, Defense);
-
C++
world.component<Defense>()
.add(flecs::OnInstantiate, flecs::Inherit);
.set(Health{100})
.set(Defense{50});
const Health *health = inst.
get<Health>();
const Defense *defense = inst.
get<Defense>();
-
C#
world.Component<Defense>()
.Add(Ecs.OnInstantiate, Ecs.Inherit);
Entity spaceship = world.Prefab("Spaceship")
.Set<Health>(new(100))
.Set<Defense>(new(50));
Entity inst = world.Entity().IsA(spaceship);
ref readonly Attack attack = ref inst.Get<Attack>();
ref readonly Defense defense = ref inst.Get<Defense>();
-
Rust
// Make Defense component inheritable
world
.component::<Defense>()
.add_trait::<(flecs::OnInstantiate, flecs::Inherit)>();
// Create prefab
let spaceship = world
.prefab()
.set(Health { value: 100 })
.set(Defense { value: 50 });
// Create prefab instance
let inst = world.entity().is_a_id(spaceship);
// Component is retrieved from instance
inst.get::<&Health>(|health| {
println!("Health value: {}", health.value);
});
// Component is retrieved from prefab
inst.get::<&Defense>(|defense| {
println!("Defense value: {}", defense.value);
});
The owns
operation can be used to tell whether a component is owned by the instance or inherited from a prefab:
-
C
if (ecs_owns(world, inst, Defense)) {
}
-
C++
if (inst.
owns<Defense>()) {
}
bool owns(flecs::id_t e) const
Check if entity owns the provided entity.
-
C#
if (inst.Owns<Defense>()) {
}
-
Rust
if inst.owns::<Defense>() {
// not inherited
}
The target_for
operation can be used to determine from which prefab (or regular entity) a component is inherited:
-
C
ecs_target_for(world, inst, Defense);
if (!inherited_from) {
}
-
C++
if (!inherited_from) {
}
flecs::entity target_for(flecs::entity_t relationship, flecs::id_t id) const
Get the target of a pair for a given relationship id.
-
C#
Entity inheritedFrom = inst.TargetFor<Defense>();
if (inheritedFrom == 0) {
}
-
Rust
let inherited_from = inst.target::<Defense>(0);
if inherited_from.is_none() {
// not inherited
}
Component Overriding
When an instance inherits a component from a prefab, it can be overridden with a value that's specific to the instance. To override a component, simply add or set it on the instance. The following example shows how:
-
C
ecs_add_pair(world,
ecs_id(Defense),
.name = "SpaceShip",
});
ecs_set(ecs, SpaceShip, Defense, {50});
ecs_set(world, inst_a, Defense, {75});
-
C++
world.component<Defense>()
.add(flecs::OnInstantiate, flecs::Inherit);
.set(Defense{50});
inst_a.set(Defense{75});
-
C#
world.Component<Defense>()
.Add(Ecs.OnInstantiate, Ecs.Inherit);
Entity spaceship = world.Prefab("Spaceship")
.Set<Defense>(new(50));
Entity instA = world.Entity().IsA(spaceship);
Entity instB = world.Entity().IsA(spaceship);
instA.Set(new Defense(75));
-
Rust
// Make Defense component inheritable
world
.component::<Defense>()
.add_trait::<(flecs::OnInstantiate, flecs::Inherit)>();
// Create prefab
let spaceship = world.prefab().set(Defense { value: 50 });
// Create prefab instance
let inst_a = world.entity().is_a_id(spaceship);
let inst_b = world.entity().is_a_id(spaceship);
// Override Defense only for inst_a
inst_a.set(Defense { value: 75 });
When a component is overridden by adding it to an instance, the component on the instance is initialized with the value from the prefab component. An example:
-
C
ecs_add_pair(world,
ecs_id(Defense),
.name = "SpaceShip",
});
ecs_set(ecs, SpaceShip, Defense, {50});
ecs_add(world, inst_a, Defense);
-
C++
world.component<Defense>()
.add(flecs::OnInstantiate, flecs::Inherit);
.set(Defense{50});
const Self & add() const
Add a component to an entity.
-
C#
world.Component<Defense>()
.Add(Ecs.OnInstantiate, Ecs.Inherit);
Entity spaceship = world.Prefab("Spaceship")
.Set<Health>(new(100))
.Set<Defense>(new(50));
Entity instA = world.Entity().IsA(spaceship);
Entity instB = world.Entity().IsA(spaceship);
instA.Add<Defense>();
-
Rust
// Make Defense component inheritable
world
.component::<Defense>()
.add_trait::<(flecs::OnInstantiate, flecs::Inherit)>();
// Create prefab
let spaceship = world.prefab().set(Defense { value: 50 });
// Create prefab instance
let inst_a = world.entity().is_a_id(spaceship);
let inst_b = world.entity().is_a_id(spaceship);
// Override Defense only for inst_a
inst_a.add::<Defense>(); // Initialized with value 50
When an override is removed, the original value of the prefab is reexposed.
Auto Overriding
When a component is configured to be inheritable, sometimes it can still be useful for a specific prefab to have the instances always own the component. This can be achieved with an auto override, which flags a component on the prefab to be always overridden on instantiation:
-
C
ecs_add_pair(world,
ecs_id(Defense),
.name = "SpaceShip",
});
ecs_set(ecs, SpaceShip, Defense, {50});
ecs_auto_override(world, SpaceShip, Defense);
ecs_owns(world, inst, Defense);
-
C++
world.component<Defense>()
.add(flecs::OnInstantiate, flecs::Inherit);
const Self & set_auto_override(const T &val) const
Set component, mark component for auto-overriding.
-
C#
world.Component<Defense>()
.Add(Ecs.OnInstantiate, Ecs.Inherit);
Entity spaceship = world.Prefab()
.SetAutoOverride<Defense>(new(50));
Entity inst = world.Entity().IsA(spaceship);
inst.Owns<Defense>();
-
Rust
// Make Defense component inheritable
world
.component::<Defense>()
.add_trait::<(flecs::OnInstantiate, flecs::Inherit)>();
// Create prefab
let spaceship = world.prefab().set_auto_override(Defense { value: 50 }); // Set & auto override Defense
// Create prefab instance
let inst = world.entity().is_a_id(spaceship);
inst.owns::<Defense>(); // true
Auto overrides can also be added to prefabs that don't have the actual component. In this case the component is not copied from the prefab (there is nothing to copy), but is added & default constructed on the instance.
This also works for prefab children. Adding an auto override to a child entity without adding the component will add & default construct the component on the instance child.
Prefab Variants
Prefabs can inherit from each other to create prefab variations without duplicating the prefab data. The following example shows a prefab and a prefab variant.
-
C
.name = "SpaceShip",
});
ecs_set(ecs, SpaceShip, Defense, {50});
ecs_set(ecs, SpaceShip, Health, {100});
.name = "Freighter",
});
ecs_set(ecs, freighter, Health, {150});
const Health *health = ecs_get(world, inst, Health);
const Defense *defense = ecs_get(world, inst, Defense);
-
C++
.set(Defense{50})
.set(Health{100});
.set(Health{150});
const Health *health = inst.
get<Health>();
const Defense *defense = inst.
get<Defense>();
const Self & is_a(entity_t second) const
Shortcut for add(IsA, entity).
-
C#
Entity spaceship = world.Prefab("Spaceship")
.Set<Defense>(new(50))
.Set<Health>(new(100));
Entity freighter = world.Prefab("Freighter")
.IsA(spaceShip)
.Set<Health>(new(150));
Entity inst = world.Entity().IsA(freighter);
ref readonly Health health = ref inst.Get<Health>();
ref readonly Defense defense = ref inst.Get<Defense>();
-
Rust
// Create prefab
let spaceship = world
.prefab_named("spaceship")
.set(Defense { value: 50 })
.set(Health { value: 100 });
// Create prefab variant
let freighter = world
.prefab_named("Freighter")
.is_a_id(spaceship)
.set(Health { value: 150 }); // Override the Health component of the freighter
// Create prefab instance
let inst = world.entity().is_a_id(freighter);
inst.get::<&Health>(|health| {
println!("Health value: {}", health.value); // 150
});
inst.get::<&Defense>(|defense| {
println!("Defense value: {}", defense.value); // 50
});
Prefab Hierarchies
When a prefab has children, the entire subtree of a prefab is copied to the instance. Other than with the instance itself where components can be inherited from a prefab, child entities never inherit components from prefab children. Prefab hierarchies are created in the same way as entity hierarchies:
-
C
.name = "SpaceShip",
});
.name = "Cockpit",
.parent = SpaceShip,
});
ecs_entity_t ecs_lookup_child(const ecs_world_t *world, ecs_entity_t parent, const char *name)
Lookup a child entity by name.
-
C++
const Self & child_of(entity_t second) const
Shortcut for add(ChildOf, entity).
flecs::entity lookup(const char *path, bool search_path=false) const
Lookup an entity by name.
-
C#
Entity spaceship = world.Prefab("Spaceship");
Entity cockpit = world.Prefab("Cockpit")
.ChildOf(spaceship);
Entity inst = ecs.Entity().IsA(spaceship);
Entity instCockpit = inst.Lookup("Cockpit");
-
Rust
let spaceship = world.prefab_named("spaceship");
let cockpit = world.prefab_named("Cockpit").child_of_id(spaceship);
// Instantiate the prefab hierarchy
let inst = world.entity().is_a_id(spaceship);
// Lookup instantiated child
let inst_cockpit = inst.lookup("Cockpit");
Prefab Slots
When a prefab hierarchy is instantiated often code will want to refer to a specific instantiated child. A typical example is a turret prefab with a turret head that needs to rotate.
While it is possible to lookup a child by name and store it on a component, this adds boilerplate and reduces efficiency. Prefab slots make this easier.
A prefab child can be created as a slot. Slots are created as relationships on the instance, with as target of the relationship the instantiated child. The slot is added as a union relationship which doesn't fragment archetypes.
The following example shows how to create and use a prefab slot:
-
C
.name = "SpaceShip",
});
.name = "Cockpit",
.parent = SpaceShip,
)
});
ecs_entity_t inst_cockpit = ecs_target(world, inst, Cockpit, 0);
-
C++
const Self & slot() const
Shortcut for add(SlotOf, target(ChildOf)).
flecs::entity target(int32_t index=0) const
Get target for a given pair.
-
C#
Entity spaceship = world.Prefab("Spaceship");
Entity cockpit = world.Prefab("Cockpit")
.ChildOf(spaceship)
.SlotOf(spaceship);
Entity inst = ecs.Entity().IsA(spaceship);
Entity instCockpit = inst.Target(cockpit);
-
Rust
let spaceship = world.prefab_named("Spaceship");
let cockpit = world.prefab_named("Cockpit").child_of_id(spaceship).slot(); // Defaults to (SlotOf, spaceship)
// Instantiate the prefab hierarchy
let inst = world.entity().is_a_id(spaceship);
// Lookup instantiated child
let inst_cockpit = inst.target_id(cockpit, 0);
Prefab Types (C++, C#)
Like entities and components, prefabs can be associated with a C++ type. This makes it easier to instantiate prefabs as it is not necessary to pass prefab handles around in the application. The following example shows how to associate types with prefabs:
-
C++
struct SpaceShip {};
world.prefab<SpaceShip>()
.set<Defense>({ 50 })
.set<Health>({ 100 });
.is_a<SpaceShip>();
-
C#
public struct Spaceship { }
world.Prefab<Spaceship>()
.Set<Defense>(new(50))
.Set<Health>(new(100));
Entity inst = world.Entity()
.IsA<Spaceship>();
Entity prefab = world.Lookup("Spaceship");
-
Rust
#[derive(Component)]
struct Spaceship;
// Create prefab associated with the spaceship type
world
.prefab_type::<Spaceship>()
.set(Defense { value: 50 })
.set(Health { value: 100 });
// Instantiate prefab with type
let inst = world.entity().is_a::<Spaceship>();
// Lookup prefab handle
let prefab = world.lookup("spaceship");