Lesson 5
Prefabs and inheritance
How a prefab gives an entity its whole type in one move, the difference between copied and inherited components, and what overriding does to storage.
A prefab is an entity used as a template. Creating an instance is adding one pair, (IsA, SpaceShip), and the instance gets the prefab’s components. What “gets” means is decided per component by its OnInstantiate trait:
- Override (the default): the component is copied into the instance’s own table.
- Inherit: the component is not copied. The instance reads the prefab’s value, so every instance shares one copy, and queries still match it.
- DontInherit: the instance doesn’t get it at all.
Watch an instance being made
MaxSpeed and Position use the default (copied); Defence is set to Inherit.
Loading the flecs debugger…
Things to notice:
- One move with the full type. Adding
(IsA, SpaceShip)moves S1 straight into[MaxSpeed, Position, (IsA, SpaceShip)]. Compare that with creating an entity and adding components one at a time, which walks through a table per component. - Inherited components aren’t in the table. The instance table has no
Defencecolumn, yet theDefendedquery returns both instances, because it matchesDefenceon the prefab. - Changing the prefab changes inherited values only. After
ship.set<Defence>({75})every instance sees 75. Aftership.set<MaxSpeed>({200}), the instances keep their copied 100. - Overriding is a move.
s1.set<Defence>({10})gives S1 its ownDefencecolumn, so it moves to a new table, and S2 is swapped into the hole. The query now returns them from two different tables.