Intermediate • Lesson 4

Prefabs & Level JSON (SceneSerializer)

Once you have a Scene, you need a fast way to stamp out copies of enemies ("prefabs") and freeze an entire level into plain JSON text so it can be saved and rebuilt later.

1. Reusable Prefabs (PrefabRegistry)

A prefab is a cookie cutter: you write the recipe for a guard or coin once, register it under a name like 'npc', and stamp out as many copies as you want.

import { PrefabRegistry } from 'maverick';

const prefabs = new PrefabRegistry();
prefabs.register('npc', (logger, config, state) => new NpcElement(logger, config, state));

const guard = prefabs.create('npc', this.Logger, { name: 'guard_1', pos: { x: 100, y: 80 } }, { color: '#00d4ff' });
PoC 1 — Stamping Out Copies with PrefabRegistry
Click "Stamp New NPC Prefab" to spawn copies from one registered recipe.

2. Saving & Rebuilding Levels (SceneSerializer)

Serialization turns live game objects into plain JSON text so you can save levels or edit them visually. SceneSerializer.deserialize() reads that JSON and uses your PrefabRegistry to rebuild every object in its exact spot.

import { SceneSerializer } from 'maverick';

const json = SceneSerializer.serialize(townScene);
const restored = SceneSerializer.deserialize(json, this.Logger, prefabs);
PoC 2 — Freeze Scene to JSON & Rebuild Live
Click "Serialize → Clear → Rebuild" to watch SceneSerializer snapshot and reconstruct the canvas.