Intermediate • Lesson 3

Scenes, Prefabs & JSON Serialization

A real game isn't just one screen—it has a Title Menu, a Town, Dungeons, and a Pause Screen. You also need a fast way to stamp out copies of enemies ("prefabs") and save an entire level into plain text so it can be reloaded later ("serialization").

Without Scenes, Prefabs & Serialization

If everything lives in one giant list, switching from the Title Screen to Level 1 means manually deleting every menu button, resetting variables, and hoping nothing was forgotten. Writing custom code to save and reload a whole level's layout by hand breaks every time you add a new enemy type.

Why Maverick Built These Tools

SceneManager swaps whole worlds cleanly (like changing theater sets between acts). PrefabRegistry acts like a cookie cutter for spawning enemies or NPCs on demand. SceneSerializer freezes an entire scene into plain JSON text and rebuilds it later.

1. Switching Scenes with SceneManager

Think of a Scene as an isolated stage set—each scene keeps its own list of elements. When you switch from 'title' to 'town', Maverick runs onExit() on the old scene and onEnter() on the new one, so menus and levels never bleed into each other.

import { Game, Scene } from 'maverick';

class TitleScene extends Scene {
  onEnter(game: Game): void {
    game.Logger.info('Entered Title');
  }
  onExit(game: Game): void {
    game.Logger.info('Left Title');
  }
}

class MyGame extends Game {
  onReady(): void {
    this.Scenes.add(new TitleScene(this.Logger, { id: 'title' }));
    this.Scenes.add(new Scene(this.Logger, { id: 'town', depthSort: true }));
    this.Scenes.switchTo('title', this);
  }
  onDisengaged(): void {}
}

2. Reusable Prefabs (PrefabRegistry)

A prefab (short for prefabricated) is a blueprint or cookie cutter. Instead of copy-pasting 15 lines of setup code every time you want another town guard or goblin, you register the recipe once 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 }, zIndex: 1 },
  { dialogId: 'welcome' }
);

3. Versioned Scene JSON (SceneSerializer)

Serialization just means turning live game objects in memory into plain text (JSON) so you can save a level to a file or database. When you load it back, SceneSerializer.deserialize() reads that text and uses your PrefabRegistry cookie cutters to rebuild every character in its exact spot—even upgrading older save formats automatically with migrate().

import { SceneSerializer } from 'maverick';

const json = SceneSerializer.serialize(townScene);
const restored = SceneSerializer.deserialize(json, this.Logger, prefabs);
Live Proof of Concept — SceneManager, PrefabRegistry & SceneSerializer
Active scene: title