---
url: /pawn/docs/guide/prefabs.md
description: >-
  Prefabs (definePrefab, engine.spawn, variants, params, named children,
  engine.prefabs, prefabs as JSON) and the Spawner behavior that spawns waves of
  them as data.
---

# Prefabs and spawning

A **prefab** is one kind of entity (a balloon, a tower, a pump): its
traits with their params, its [presets](./behaviors.md#presets), its look and its children. A preset
says how an entity behaves; a prefab says what it is, and may use presets.
`engine.spawn(prefab, overrides)` makes a whole entity from one in a
single call:

```ts
import { definePrefab, defineTrait, Position, Shape } from "@pawnjs/core";

const Health = defineTrait({
  name: "health",
  params: { hp: { default: 100, min: 0 } },
});

const Barrel = definePrefab({
  name: "barrel",
  traits: [Position, [Shape, { kind: "cylinder" }]],
});

export const Tower = definePrefab({
  name: "tower",
  traits: [Position, [Shape, { kind: "box" }], [Health, { hp: 50 }]],
  presets: [Button3D],
  children: [[Barrel, { position: { y: 1 } }]],
});

const tower = engine.spawn(Tower, {
  position: { x: 2, z: -1 },
  health: { hp: 80 },
  hoverable: { tint: "#f59e0b" },
});
```

`engine.spawn` also takes a prefab's registered name, and a third
argument (below). `spawnPrefab(engine, prefab, overrides, options)` is the
same as a function, for code that holds an engine but is not a method.

* `description` says what the prefab is in a sentence (`"Storage rack,
  2.4 m tall."`), for people and agents reading a catalog. It is on
  `prefab.description` (`""` for none), and a variant without one (or
  with `""`) keeps its base's.
* `traits` lists traits and behaviors made by `defineTrait` or
  `defineBehavior`, alone or with params, each at most once (also across
  the presets' behaviors). Behavior plugins install as usual.
* `visual(entity)` builds the entity's `Visual` once its traits are on,
  so it can read them (a mesh in the color a trait holds). It is code, not
  data; for a look that snapshots save, list `Shape` or `Model` instead.
  Share its geometries and materials between entities, or free those
  one entity makes for itself with `disposeVisual` (see
  [Rebuilding the look](#rebuilding-the-look)).
* `children` are prefabs, alone or with overrides, spawned under the
  entity with `ChildOf`.
* Overrides are keyed by trait or behavior name and merged over the
  prefab's params; lists and objects are copied per entity. An override
  may also name a trait the prefab lacks but `engine.traits` has
  (`position`, `tint`, `rigid-body`), which is then added.
* Overrides are type-checked: a name the prefab does not have
  (`helth`), or a param of the wrong type, is a TypeScript error. Core
  traits (`position`, `rotation`, `scale`, `tint`, `shape`, `light`,
  `model`) may always be named; other registered traits go through a
  spawn by registered name, which is not checked.
* The third argument places the entity: `{ parent, id, scope }` puts it
  under a parent, gives it an `EntityId` and adds it to a
  [scope](./engine.md#scopes).
* A behavior in the prefab that adds a default trait (`FollowPath` adds
  `Position`) gets the one the prefab or an override gives.

Params are checked like a preset's: `definePrefab` throws on bad params of
its traits and children, and a spawn on an override naming an unknown
trait or not fitting its trait, before anything is spawned.

## Rebuilding the look

A `visual` reads its traits once, when the entity spawns. When a trait
describes the whole look (a sign's size, a track's course), list it in
`rebuildOn`: setting or adding it, by hand or by a snapshot restore,
builds the `Visual` again. The new one takes the old one's place in the scene, under
the same parent and over the same children. `disposeVisual` frees a
`Visual` the prefab built once it is gone: replaced by a rebuild or by
hand, removed with its entity, or when the engine is disposed.

```ts
import { definePrefab, defineTrait, disposeObject3D, Position } from "@pawnjs/core";
import { BoxGeometry, Mesh, MeshStandardMaterial } from "three";

const Board = defineTrait({
  name: "board",
  params: { width: { default: 4, min: 1 }, color: { default: "#38bdf8" } },
});

const Billboard = definePrefab({
  name: "billboard",
  traits: [Position, Board],
  visual: (entity) => {
    const { width, color } = entity.get(Board) ?? { width: 4, color: "#fff" };
    return new Mesh(
      new BoxGeometry(width, 2, 0.2),
      new MeshStandardMaterial({ color }),
    );
  },
  rebuildOn: [Board],
  disposeVisual: disposeObject3D,
});

const board = engine.spawn(Billboard);
board.set(Board, { width: 8 }); // a new, wider mesh; the old one is freed
```

* Only traits the prefab lists may be in `rebuildOn`. Each one makes
  every `updateEach` that writes it compare values, so keep traits
  written every frame out.
* A `Visual` set by hand wins, as for `Shape`: the prefab's is freed and
  no longer rebuilt.
* A variant without a `visual` of its own keeps its base's `rebuildOn`
  and `disposeVisual`; one with its own visual starts without them.

## Variants

`extends` makes a prefab a variant of another: it starts from the base's
traits, presets, look, children and params. Its own traits replace the
params of the same trait in the base, merged over them, or add new ones.

```ts
const Enemy = definePrefab({
  name: "enemy",
  traits: [Health, FollowPath, Shape, [Burst, { on: "died" }]],
});

export const Tank = definePrefab({
  name: "enemy-tank",
  extends: Enemy,
  traits: [
    [Health, { hp: 16, max: 16 }],
    [FollowPath, { speed: 0.9 }],
    [Shape, { kind: "box", color: "#7c3aed" }],
    [Burst, { count: 18 }], // still on "died"
  ],
});
```

A variant cannot take a trait away; put what not every variant has in the
variants instead.

## Prefab params

`params` gives names to params of the prefab's traits, so a spawn sets one
value in several places without knowing which traits hold it. Each name
lists `"trait.param"` paths, checked by TypeScript and by `definePrefab`:

```ts
const Balloon = definePrefab({
  name: "balloon",
  traits: [Shape, [Burst, { on: "click" }]],
  params: { color: ["shape.color", "burst.color"] },
});

engine.spawn(Balloon, { color: "#f43f5e" });
```

A param's value has the type of its first path. A trait named in the same
overrides wins over a param (`{ color: "red", shape: { color: "blue" } }`
gives a blue shape and a red burst). A param may not be named like a trait
or a child of the prefab.

## Named children

`children` is a list, or an object that names each child. Spawn
overrides then reach a named child by its name, and `childNamed` finds it
under a spawned entity:

```ts
const Turret = definePrefab({
  name: "turret",
  traits: [Position, [Shape, { kind: "cylinder" }], Spin],
});

const Tower = definePrefab({
  name: "tower",
  traits: [Position, [Shape, { kind: "box" }]],
  children: { turret: [Turret, { position: { y: 1 } }] },
});

const tower = engine.spawn(Tower, { turret: { spin: { speed: 3 } } });
const turret = childNamed(tower, "turret");
```

A child's own prefab params work under its name too (`{ turret: { color:
"#f00" } }` for a turret with a `color` param), and win over the parent
prefab's override of the same trait. A variant's named child replaces the
base's child of the same name.

## Which prefab an entity is

Every entity spawned from a prefab gets `PrefabOf`, which holds the
prefab's name and its name among its parent's children (`slot`), and
snapshots save. It also gets the prefab's `tag`, and the tags of the
prefabs it is a variant of, for queries:

```ts
for (const enemy of engine.world.query(Enemy.tag, Position)) {
  // every enemy, variants included
}
Enemy.is(entity); // whether it was spawned from Enemy or a variant
```

`isPrefab(value)` tells a prefab from anything else.

## Prefabs by name

`engine.prefabs` is a `PrefabRegistry`. Register prefabs there and data
can name them: `engine.spawn` takes a name, and a [`Spawner`](#spawner)'s
waves list names.

```ts
engine.prefabs.register(Runner, Tank);
engine.spawn("tank", { position: { x: 2 } });
engine.prefabs.get("tank"); // Tank
```

Registering a prefab also registers its traits and behaviors (its
base's and children's too) in `engine.traits`, so
[snapshots](/guide/snapshots) save and restore them. Registering the same
prefab again does nothing; another prefab under a taken name throws, as
does a trait of it whose name another trait has, and so does spawning a
name nothing is registered as. For hot module replacement, which runs
`definePrefab` again, `engine.prefabs.replace(prefab)` puts the new prefab
and its traits in place of the old ones; entities spawned before keep
what they have.

## Prefabs as data

`prefabToJSON(prefab)` writes a prefab as plain data, for a file, an
editor or an agent, and `prefabFromJSON(engine, json)` reads it back.
Traits are named as `engine.traits` knows them, and the base and children
as `engine.prefabs` does, so register them first:

```ts
import { prefabFromJSON, prefabToJSON } from "@pawnjs/core";

const json = prefabToJSON(Tank);
// { name: "enemy-tank", extends: "enemy", traits: { health: { hp: 16, max: 16 } } }

const Boss = prefabFromJSON(engine, {
  name: "enemy-boss",
  extends: "enemy",
  traits: { health: { hp: 80, max: 80 }, shape: { kind: "torus" } },
});
engine.prefabs.register(Boss);
```

* A variant is written as its base's name and what it adds or changes;
  its `description` only when it has its own.
* Presets are written as their behaviors, so the prefab read back lists
  them as traits.
* A prefab with its own `visual` cannot be written: that is code. Use
  `Shape` or `Model` for a look that is data.
* `prefabFromJSON` checks the data like `definePrefab` and throws with
  every problem found. Its overrides are checked when spawned, not by
  TypeScript.

`toJSONSchema(prefab)` describes the overrides a prefab's spawns take, as
JSON Schema: its traits and behaviors, the core traits (`CORE_TRAITS`,
which any prefab's overrides may name), its params and its named
children, with the prefab's `description`. To read a prefab in code,
`prefabTraits(prefab)` lists its traits and behaviors (its presets' ones
too) by name, `prefabParamSpec(prefab, "color")` gives a prefab param's
spec, and `prefabValue(prefab, "trait.param")` gives the value a spawn
without overrides gets:

```ts
import { prefabTraits, prefabValue } from "@pawnjs/core";

[...prefabTraits(Tank).keys()]; // ["health", "follow-path", "shape", "burst"]
prefabValue(Tank, "health.hp"); // 16
```

`resolvePrefab(prefab, overrides, engine)` applies overrides without
spawning: each entity's traits with their params, its children, and what
is wrong with the overrides. `resolvedValue` reads a param from it:

```ts
import { resolvedValue, resolvePrefab } from "@pawnjs/core";

const tank = resolvePrefab(Tank, { health: { hp: 30 } }, engine);
tank.problems; // []
resolvedValue(tank, "health.hp"); // 30
tank.traits.map(({ trait }) => trait.name); // ["health", "follow-path", "shape", "burst"]
```

[Snapshots](/guide/snapshots#entities-from-prefabs) save an entity from a
registered prefab as the prefab's name and what differs from it.

## Spawner

`Spawner` spawns waves of registered prefabs at its entity's world
position, such as enemies in a game or vehicles in a simulation. The
waves are data:

```ts
import { Position, Spawner } from "@pawnjs/core";

engine.prefabs.register(Runner, Tank);
const gate = engine.world.spawn(
  Position({ x: -6 }),
  Spawner({
    waves: [
      { spawns: [{ prefab: "runner", count: 6 }], every: 1 },
      {
        spawns: [
          { prefab: "runner", count: 8 },
          { prefab: "tank", count: 2, overrides: { health: { hp: 30 } } },
        ],
        every: 0.8,
      },
    ],
    pause: 3,
    overrides: { "follow-path": { points } },
  }),
);
engine.events.on(gate, "spawn", ({ entity }) => track(entity));
engine.events.on(gate, "spawnerend", () => win());
```

* Each wave starts `pause` seconds after the previous one ended (the
  first `pause` seconds after the spawner is added). It spawns its groups
  in order, one entity every `every` seconds, the first at once.
* A wave ends once all its entities are destroyed. With
  `enableWaitForClear: false` it ends as soon as the last one is spawned.
* Spawned entities get `overrides`, then their group's `overrides`, over
  the prefab's params, and `position` at the spawner unless an override
  sets it. Overrides name traits, children or prefab params
  (`{ color: "#f00" }`), as in `engine.spawn`; the type is
  `SpawnOverrides`. They get `SpawnedBy(spawner)` and join the spawner's
  [scope](./engine.md#scopes).
* The spawner gets entity events: `wavestart` and `waveend` with the
  1-based `wave`, `spawn` with the `entity` and `wave`, and `spawnerend`
  after the last wave.
* `wave`, `stage` (`"waiting"`, `"spawning"`, `"clearing"`, `"done"`),
  `time` and `spawned` hold the progress, so snapshots keep it. Remove
  `Spawner` to stop it.
* Time is scaled engine time. A prefab that is not registered stops the
  spawner with an error.
