Scene Files and Prefabs
A level is data: which entities exist, which components they have, and the values of those components. Storing it in a file the editor writes and the runtime reads keeps designers out of C++ and lets the same engine run many levels. Two ideas make scene files manageable:
- A prefab (Unity's term; Unreal calls them Blueprint classes, Godot packed scenes, flecs prefabs) is a reusable template: "a goblin has 30 health, speed 2.5 and the goblin sprite".
- An instance in the level refers to a prefab and stores only its overrides: "this goblin stands at (7, 2) and has 60 health".
Change the prefab and every instance that did not override that value follows. That is the single most important property of a scene format, and the one homegrown formats most often lose.
A tiny text format
Real engines use JSON, YAML (Unity), their own text formats (Godot's .tscn, Unreal's .uasset is binary) or USD. The ideas are easier to see in a minimal line-based format, so we parse this one:
prefab Goblin
Health 30
Speed 2.5
Sprite goblin.png
end
entity hero
Position 0 0
Health 100
end
entity g1 : Goblin
Position 5 2
end#include <iostream>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using Components = std::map<std::string, std::string>; // component name -> raw value text
struct EntityDef { std::string name, prefab; Components components; };
struct SceneFile {
std::map<std::string, Components> prefabs;
std::vector<EntityDef> entities;
};
SceneFile parse(const std::string& text) {
SceneFile scene;
std::istringstream in(text);
std::string line;
int lineNo = 0;
Components* current = nullptr;
auto fail = [&](const std::string& msg) { throw std::runtime_error("line " + std::to_string(lineNo) + ": " + msg); };
while (std::getline(in, line)) {
lineNo++;
if (auto hash = line.find('#'); hash != std::string::npos) line.erase(hash); // comments
std::istringstream words(line);
std::string head;
if (!(words >> head)) continue; // blank line
if (head == "prefab" || head == "entity") {
if (current) fail("missing 'end' before '" + head + "'");
std::string name, colon, base;
words >> name >> colon >> base;
if (head == "prefab") { current = &scene.prefabs[name]; continue; }
if (!colon.empty() && colon != ":") fail("expected ':' after entity name");
if (!base.empty() && !scene.prefabs.count(base)) fail("unknown prefab '" + base + "'");
scene.entities.push_back({name, base, {}});
current = &scene.entities.back().components;
} else if (head == "end") {
if (!current) fail("'end' without a block");
current = nullptr;
} else {
if (!current) fail("component '" + head + "' outside a block");
std::string rest;
std::getline(words >> std::ws, rest);
rest.erase(rest.find_last_not_of(" \t") + 1); // trim trailing spaces
(*current)[head] = rest;
}
}
if (current) fail("file ended inside a block");
return scene;
}
// Instantiate: start from the prefab's values, then apply the entity's overrides.
Components resolve(const SceneFile& s, const EntityDef& e) {
Components c = e.prefab.empty() ? Components{} : s.prefabs.at(e.prefab);
for (auto& [k, v] : e.components) c[k] = v;
return c;
}
const char* kLevel = R"(# level 1
prefab Goblin
Health 30
Speed 2.5
Sprite goblin.png
end
entity hero
Position 0 0
Health 100
end
entity g1 : Goblin
Position 5 2
end
entity g2 : Goblin
Position 7 2
Health 60 # a tougher goblin
end
)";
int main() {
SceneFile scene = parse(kLevel);
for (const EntityDef& e : scene.entities) {
std::cout << e.name << (e.prefab.empty() ? "" : " (" + e.prefab + ")") << ":";
for (auto& [k, v] : resolve(scene, e)) std::cout << " " << k << "=[" << v << "]";
std::cout << "\n";
}
for (const char* broken : {"entity x : Orc\nend\n", "prefab A\n Health 1\nentity b\nend\n", " Speed 3\n"}) {
try { parse(broken); } catch (const std::exception& ex) { std::cout << "error: " << ex.what() << "\n"; }
}
}hero: Health=[100] Position=[0 0]
g1 (Goblin): Health=[30] Position=[5 2] Speed=[2.5] Sprite=[goblin.png]
g2 (Goblin): Health=[60] Position=[7 2] Speed=[2.5] Sprite=[goblin.png]
error: line 1: unknown prefab 'Orc'
error: line 3: missing 'end' before 'entity'
error: line 1: component 'Speed' outside a block
Two habits worth copying: every error carries a line number, and the parser rejects unknown prefabs at load time instead of producing a half-built entity at runtime.
Saving: write only the overrides
When the editor saves an instance, it must write only values that differ from the prefab. If it wrote every value, the instance would freeze the prefab's current numbers, and a later change to the prefab (say, goblin health 30 → 40) would silently not reach it.
#include <iostream>
#include <map>
#include <string>
using Components = std::map<std::string, std::string>;
Components overridesOnly(const Components& prefab, const Components& instance) {
Components out;
for (auto& [k, v] : instance) {
auto it = prefab.find(k);
if (it == prefab.end() || it->second != v) out[k] = v; // new or changed
}
return out;
}
void printBlock(const std::string& header, const Components& c) {
std::cout << header << "\n";
for (auto& [k, v] : c) std::cout << " " << k << " " << v << "\n";
std::cout << "end\n";
}
int main() {
Components goblin = {{"Health", "30"}, {"Speed", "2.5"}, {"Sprite", "goblin.png"}};
// The live entity in the editor after a designer moved it and changed its health:
Components live = {{"Health", "60"}, {"Position", "7 2"}, {"Speed", "2.5"}, {"Sprite", "goblin.png"}};
printBlock("entity g2 : Goblin", overridesOnly(goblin, live));
goblin["Speed"] = "3.0"; // later, the prefab is rebalanced
Components reloaded = goblin;
for (auto& [k, v] : overridesOnly({{"Health", "30"}, {"Speed", "2.5"}, {"Sprite", "goblin.png"}}, live)) reloaded[k] = v;
std::cout << "after rebalancing, g2 speed = " << reloaded["Speed"] << ", health = " << reloaded["Health"] << "\n";
}entity g2 : Goblin
Health 60
Position 7 2
end
after rebalancing, g2 speed = 3.0, health = 60
The saved block has only Health and Position, so the prefab's new speed reaches g2 while its custom health is kept.
Choosing a real format
| Format | Good for | Watch out for |
|---|---|---|
| JSON (nlohmann/json, RapidJSON, simdjson) | quick start, tools in any language | no comments in strict JSON; merge conflicts on big arrays |
| YAML | readable, used by Unity scenes | slow parsers, surprising type rules |
Custom text (like above, Godot .tscn) |
diffable, tailored to your data | you maintain the parser |
| Binary (see Binary Serialization) | shipping builds, fast loads | not mergeable; needs tooling to inspect |
| glTF 2.0 | meshes, materials, node hierarchies, animations from DCC tools | it describes assets, not your gameplay components |
| OpenUSD | large pipelines, layered edits by many people | heavy dependency |
A common split: text in the repository, binary in the build. The editor saves text so merges and code reviews work; a cook step converts it to a binary blob the runtime loads in one read.
Here is the same goblin as a JSON scene entry, as many custom engines store it:
{
"entities": [
{ "name": "g2", "prefab": "prefabs/goblin.prefab",
"overrides": { "Position": [7, 2], "Health": 60 } }
]
}Tip: Give every entity in a scene file a stable ID (a GUID or an increasing number stored in the file), not just a name. References between entities ("this door is opened by that lever") and prefab overrides on nested children use those IDs, and they must survive renames and reordering.
Note: Nested prefabs (a prefab containing instances of other prefabs, each with overrides) are where scene formats get hard: override paths, ID remapping and change propagation. Unity, Unreal and Godot each spent years on this. If your game needs deep nesting, that alone is a good argument for using an existing engine or editor.
Test yourself
Why should a saved prefab instance contain only overridden values?
- To save disk space only
- So later changes to the prefab still reach instances that didn't override those values
- Because the parser cannot read full blocks
- To make loading slower
In the parser, what happens with entity x : Orc when no Orc prefab exists?
- The entity is created without components
- Loading fails with a line-numbered error
- Orc is created automatically
- The line is skipped
What is a common way to combine readable and fast scene formats?
- Use only binary everywhere
- Store text in source control and cook it to binary for builds
- Store JSON in the shipped game and parse it each frame
- Hand-edit binary files