Reuse a group of things: prefabs
A prefab is a group of things saved once and placed many times. Make one in the editor from a selection, or in code with definePrefab, and spawn it with world.spawnPrefab.
ts
// in src/rules.ts
import { defineIds, definePrefab, type Rules, prefabsFrom, type World } from '@v12-engine/engine'
export const UNIT = defineIds('scout', 'tower', 'wall')
/** An outpost: a tower with walls round it, and a scout on guard, placed as one */
const outpost = definePrefab({
id: 'mygame.outpost',
contents: {
objects: [
{ type: UNIT.tower, x: 0, z: 0 },
{ type: UNIT.wall, x: -2, z: -2 },
{ type: UNIT.wall, x: 2, z: -2 },
{ type: UNIT.scout, x: 0, z: 2, facing: Math.PI }
],
camps: [{ x: 4, z: 4, units: [UNIT.scout, UNIT.scout] }],
areas: [{ id: 'yard', shape: { kind: 'circle', x: 0, z: 0, radius: 4 } }]
}
})
// the prefabs the designers made in the editor, as the game's own
const designed = prefabsFrom(import.meta.glob('./prefabs/*.json', { eager: true, import: 'default' }), { prefix: 'mygame' })
export const rules: Rules = {
id: 'my-game',
name: 'My game',
units: [
{ id: UNIT.scout, name: 'Scout', kind: 'unit', radius: 0.4, sight: 10, stats: { health: 100, moveSpeed: 5 } },
{ id: UNIT.tower, name: 'Tower', kind: 'building', radius: 1, sight: 10, footprint: { w: 2, d: 2 }, stats: { health: 600 } },
{ id: UNIT.wall, name: 'Wall', kind: 'building', radius: 0.5, sight: 2, footprint: { w: 1, d: 1 }, stats: { health: 500 } }
],
prefabs: [outpost, ...designed],
victory: null
}
export function onStart(world: World): void {
// as one: turned a quarter, for player 2, names made free, the area under an id of its own (yard#1)
world.spawnPrefab('mygame.outpost', { at: { x: 40, z: 40 }, owner: 2, facing: Math.PI / 2 })
world.spawnPrefab('mygame.outpost', { at: { x: 20, z: 60 }, owner: 2, without: { camps: [0] } })
}Done: two outposts for player 2, one turned a quarter, one without its camp. Each gets its own area id (yard#1).
In the editor
- Select things and click Save as a prefab (a name, tags, with or without the ground).
- Place it from Place › Prefabs. [ and ] turn it, R a quarter turn, Shift+wheel a step.
- A placed instance stays linked. In the Inspector: Update pulls the latest prefab and keeps your changes, Revert remakes it, Apply writes it back as the prefab, Unpack lets its parts go.
- Right-click a prefab to edit it on its own stage, or Make a variant of it….
Reference
| Option / feature | What it does |
|---|---|
contents | objects (with an owner slot), camps, areas, scenery; or a function of the place and world. |
without | Leave parts out when spawning. |
scale, facing, owner | Size, turn and owner of the spawned copy. |
prefabsFrom(files, { prefix }) | Load the editor's prefab files as your game's. |
| Nested prefabs | A prefab inside a prefab stays linked to its source. |
| Variants | A source plus overrides (variant.over); editor.clipboard.makeVariant(of, as). |
See Saves, mods, data and components and Placing in the editor.