Engine-neutral save and load with Godot and Python code: what to serialize, slots and autosave, atomic writes and versioned migration. Use for save/load or a…
Save systems
A save file is a serialized snapshot of game state that must survive crashes, restarts and
patches. The hard parts are choosing what to save, writing it so a crash mid-save cannot
destroy it, and reading old saves after an update. This skill owns the file: format, writes,
versioning, slots and location. Genre skills decide what goes in it.
When to use
Persisting progress: stats, inventory ids, world flags, settings, positions, seeds.
Save slots, quicksave, autosave, crash-safe writes, backups.
Old saves failing after a code or content change.
Not this skill: Roblox cloud persistence (roblox-datastores), the data model itself
(godot-resources, unity-scriptableobjects), rebinding data shape (input-systems), save
screens and rollback in a visual novel (visual-novel).
Core workflow
Find what exists. Grep for the current save code (FileAccess, ConfigFile,
ResourceSaver, PlayerPrefs, SaveGameToSlot, persistentDataPath) and any shipped
saves. If players already have saves, every change below needs a migration.
Save data, not objects. Ids, numbers, flags and the RNG seed; rebuild nodes and objects
from that data on load. Live references and node paths do not survive a refactor.
Stamp an integer version in every save from the first release.
Start with JSON (readable, diffable, easy to migrate); move to binary only for size or
speed you have measured.
Write atomically: temp file, keep the previous save as .bak, rename into place.
Load defensively: parse, read version, refuse newer saves, migrate older ones step by
step, validate, then apply. Fall back to the backup on failure and tell the player.
Autosave at safe boundaries (checkpoint, level change), throttled, into its own slot.
Run the checks below, then ask the user for the quit-and-relaunch test.
Patterns
1. State as plain data
func capture_state() -> Dictionary:
return {
"version": SAVE_VERSION,
"player": { "hp": player.hp, "pos": [player.position.x, player.position.y] },
"inventory": player.inventory.to_array(), # ids + counts, not Item nodes
"flags": world.flags,
"seed": world.seed, # regenerate procedural content
}
func apply_state(data: Dictionary) -> void: # rebuild from data; no live references
player.hp = int(data["player"]["hp"])
player.position = Vector2(data["player"]["pos"][0], data["player"]["pos"][1])
player.inventory.from_array(data["inventory"])
world.flags = data["flags"]
2. Atomic, crash-safe write (temp + rename)
# Godot 4.7. Write a temp file, keep the previous save as .bak, then rename.
func save_atomic(path: String, data: Dictionary) -> Error:
var tmp := path + ".tmp"
var f := FileAccess.open(tmp, FileAccess.WRITE)
if f == null:
return FileAccess.get_open_error() # disk full, read-only, no permission...
if not f.store_string(JSON.stringify(data)):
return ERR_FILE_CANT_WRITE
f.close() # flushes Godot's buffer to the OS
if FileAccess.file_exists(path):
DirAccess.rename_absolute(path, path + ".bak") # keep the last good save
return DirAccess.rename_absolute(tmp, path)
func load_save(path: String) -> Dictionary: # empty = nothing loadable
for p in [path, path + ".bak"]: # .bak covers a crash between renames
if FileAccess.file_exists(p):
var data = JSON.parse_string(FileAccess.get_file_as_string(p))
if data is Dictionary and data.has("version"):
data["version"] = int(data["version"]) # JSON numbers load as float
return data
return {}
# WRONG: opening `path` directly and writing in place — a crash mid-write leaves a
# truncated, unloadable save and destroys the player's progress.
A crash leaves the old save, the new one, or (between the two renames) only the .bak, which
the loader tries next. rename() replaces the target atomically on POSIX within one volume, but
Godot's Windows rename_absolute deletes the target and then moves, so Windows relies on the
.bak as well. Neither flush() nor close() calls fsync, so a power cut right after a save
can still lose the newest file. Check every returned Error and tell the player when a save
fails.
3. Versioned load with migration
SAVE_VERSION = 3
def load_save(raw_bytes):
data = parse(raw_bytes) # JSON/binary -> dict
v = int(data.get("version", 1)) # no field = the first shipped schema
if v > SAVE_VERSION:
raise NewerSaveError(v) # save is from a newer build; refuse
while v < SAVE_VERSION: # apply migrations in order, v -> v+1
data = MIGRATIONS[v](data)
v += 1
data["version"] = v
validate(data) # check required keys / ranges
return data
# Each migration is a pure function from one version's shape to the next.
def migrate_1_to_2(d):
d["flags"] = {k: True for k in d.pop("completed_quests", [])} # list -> set-map
return d
def migrate_2_to_3(d):
d.setdefault("difficulty", "normal") # new field: old saves get the default
return d
MIGRATIONS = {1: migrate_1_to_2, 2: migrate_2_to_3}
Keep every migration forever; deleting one strands every save of that version.
4. Slots and throttled autosave
const SLOT_PATH := "user://save_%d.json" # manual slots 0..N
const AUTOSAVE_PATH := "user://autosave.json" # separate file: never clobbers a slot
var _autosave_cooldown := 0.0
func autosave_if_due(dt: float) -> void:
_autosave_cooldown -= dt
if _autosave_cooldown <= 0.0:
save_atomic(AUTOSAVE_PATH, capture_state())
_autosave_cooldown = 60.0 # at most once a minute; also save on checkpoints
5. Round-trip and corruption test (headless)
# tools/save_roundtrip_test.gd: godot --headless --path . --script res://tools/save_roundtrip_test.gd
extends SceneTree
const PATH := "user://test_save.json"
func _initialize() -> void:
var saver = load("res://save.gd").new() # the game's save_atomic / load_save
var ok := true
var first := {"version": 3, "player": {"hp": 7, "pos": [1.5, -2.0]}, "flags": {"met_guard": true}}
var second := first.duplicate(true)
second["player"]["hp"] = 4
ok = ok and saver.save_atomic(PATH, first) == OK
ok = ok and saver.save_atomic(PATH, second) == OK # first is now the .bak
var loaded: Dictionary = saver.load_save(PATH)
# Compare fields, not whole Dictionaries: JSON turned hp 4 into 4.0, and 4 != 4.0 there.
ok = ok and loaded.get("version") is int and loaded["player"]["hp"] == 4
ok = ok and loaded["player"]["pos"] == [1.5, -2.0] and loaded["flags"] == second["flags"]
var f := FileAccess.open(PATH, FileAccess.WRITE) # simulate a truncated primary
f.store_string("{\"version\": 3, \"pla")
f.close()
ok = ok and saver.load_save(PATH)["player"]["hp"] == 7 # fell back to .bak
for p in [PATH, PATH + ".bak", PATH + ".tmp"]:
DirAccess.remove_absolute(ProjectSettings.globalize_path(p))
print("SAVE_ROUNDTRIP ", "ok" if ok else "FAIL")
quit(0 if ok else 1)
Point res://save.gd at the game's own save script. The truncated file makes Godot print
Parse JSON failed; that line is expected here, and the test passes only if the .bak loads.
Check it
Run the round-trip test: it must print SAVE_ROUNDTRIP ok.
Keep one real save per shipped version in a fixtures folder and load each through the
migration chain in a test after every schema change.
Load a save stamped with a newer version and confirm it is refused with a message, not
half-loaded.
Grep the save path for engine objects (Node, Resource, var_to_str, store_var with
objects allowed); there should be none.
Ask the user to save mid-level, quit the game fully, relaunch, load, and report anything that
differs (position, inventory, flags, quest state). For Steam Cloud, ask them to repeat it on a
second machine and report whether the save arrived.
Gotchas
No version field. The first patch turns every existing save into guesswork.
Serializing engine objects or node paths ties saves to scene structure; a rename breaks
every old save.
In-place writes corrupt saves on a crash or power loss. Write a temp file, keep a .bak.
Godot JSON turns every number into a float: version 3 loads as 3.0, so
MIGRATIONS.has(data["version"]) is false, whole-Dictionary == against the original fails,
and integers above 2^53 (64-bit ids, big seeds) lose digits. Convert with int(), store big ids
as strings, or wrap the state with JSON.from_native() / JSON.to_native().
JSON.parse_string on a corrupt file logs an engine error and returns null. Use a
JSON instance and parse() when you need the error line and message for the player or log.
Loading objects from save files. Godot str_to_var or get_var with objects allowed, a
ConfigFile holding objects, or ResourceLoader on a .tres the player can swap will create
an object whose script runs during the load. Saves get shared online; keep them plain data.
Floats and locale. Hand-built text formats can write comma decimals in some locales. Use
the engine's JSON or another locale-invariant serializer.
Autosave clobbering a manual save, or firing mid-combat and saving an inconsistent state.
Use a dedicated slot and safe boundaries.
Saving next to the executable: often read-only, and replaced by updates. Use the engine's
per-user folder (see the reference).
Trusting client saves online. A local save is player-controlled; never use it as the
authority for multiplayer or economy state.
References
references/versioning-and-migration.md: read when evolving a schema (additive, rename and
removal migrations), keeping a save corpus, rotating backups, choosing JSON vs binary,
writing load-time validation, finding where saves live per engine, or setting up Steam Cloud.
Related skills
roblox-datastores: cloud persistence, request limits, session locking.
godot-resources, unity-scriptableobjects: the data model you serialize.
procedural-gen: saving the seed and generator version instead of the world.
rpg, survival-crafting, visual-novel: what each genre puts in the save.
steam-publish: the Steamworks app admin pages where Steam Cloud is configured.
Version notes
Last verified: 2026-11-11.
Godot 4.7: FileAccess.store_string returns bool; JSON.from_native/to_native exist;
Windows DirAccess.rename deletes the target before moving
(drivers/windows/dir_access_windows.cpp). The round-trip test above ran on 4.7.2 headless.
Steam Cloud: files sync after the game exits and before the next launch; byte and file quotas
must be set before it works; Cross-Platform is the recommended OS setting for Auto-Cloud roots;
Dynamic Cloud Sync can change files mid-session
(https://partner.steamgames.com/doc/features/cloud).
39don't have the plugin yet? install it then click "run inline in claude" again.
extracted implicit decision logic into explicit if-else branches, formalized inputs with env/path guidance, expanded
a save file is a serialized snapshot of game state that must survive crashes, restarts and patches. this skill covers what to serialize, how to write it safely so a crash mid-save cannot destroy it, and how to read old saves after an update. own the file format, writes, versioning, slots and location here. genre skills decide what goes in the save.
use this skill when persisting progress (stats, inventory ids, world flags, settings, positions, seeds), implementing save slots or quicksave or autosave, handling crash-safe writes and backups, or migrating saves across code or content changes.
do not use this for roblox cloud persistence (roblox-datastores), the data model itself (godot-resources, unity-scriptableobjects), input rebinding (input-systems), or visual novel save screens and rollback (visual-novel).
game state to capture
file system access
external dependencies
version and schema
existing saves
1. find and audit existing saves
grep the codebase for file writes: FileAccess, ConfigFile, ResourceSaver, PlayerPrefs, SaveGameToSlot, persistentDataPath, or any pickle/json dumps. list all current save locations and formats. if players have shipped saves, record the current schema version (call it v1 if none exists).
outputs: list of save locations, current format (json/binary/engine-specific), current schema shape.
2. design the save schema as plain data
define a function that returns a dictionary (or dict in python) with version, player state, inventory, flags, and seed. include only serializable primitives: strings, numbers, arrays, dicts. no node references, no live objects, no var_to_str() output.
example in godot:
func capture_state() -> Dictionary:
return {
"version": SAVE_VERSION,
"player": { "hp": player.hp, "pos": [player.position.x, player.position.y] },
"inventory": player.inventory.to_array(),
"flags": world.flags,
"seed": world.seed,
}
example in python:
def capture_state():
return {
"version": SAVE_VERSION,
"player": {"hp": player.hp, "pos": [player.position.x, player.position.y]},
"inventory": player.inventory.to_array(),
"flags": world.flags,
"seed": world.seed,
}
outputs: schema dict with all required fields; version field set to current save_version.
3. implement atomic, crash-safe write
write to a temp file first, flush to disk, keep the previous save as .bak, then rename the temp file into place. this ensures a crash mid-write does not destroy the previous save.
godot 4.7:
func save_atomic(path: String, data: Dictionary) -> Error:
var tmp := path + ".tmp"
var f := FileAccess.open(tmp, FileAccess.WRITE)
if f == null:
return FileAccess.get_open_error()
if not f.store_string(JSON.stringify(data)):
return ERR_FILE_CANT_WRITE
f.close()
if FileAccess.file_exists(path):
DirAccess.rename_absolute(path, path + ".bak")
return DirAccess.rename_absolute(tmp, path)
python:
import json
import os
from pathlib import Path
def save_atomic(path, data):
tmp = path + ".tmp"
try:
with open(tmp, "w") as f:
json.dump(data, f)
if os.path.exists(path):
os.replace(path, path + ".bak")
os.replace(tmp, path)
return True
except (IOError, OSError) as e:
return False
outputs: save file at path, previous save as path.bak, no .tmp file left behind.
4. implement defensive load with fallback
load from the primary path; if it is missing or corrupt, try the .bak. parse, check version, refuse newer saves, migrate older ones step by step, validate required keys, and return the data dict. if all files fail, return an empty dict and log a message.
godot 4.7:
func load_save(path: String) -> Dictionary:
for p in [path, path + ".bak"]:
if FileAccess.file_exists(p):
var json_obj = JSON.new()
var text = FileAccess.get_file_as_string(p)
var error = json_obj.parse(text)
if error == OK and json_obj.data is Dictionary:
var data = json_obj.data
if data.has("version"):
data["version"] = int(data["version"])
return data
return {}
python:
import json
def load_save(path):
for p in [path, path + ".bak"]:
try:
with open(p, "r") as f:
data = json.load(f)
if isinstance(data, dict) and "version" in data:
data["version"] = int(data["version"])
return data
except (IOError, json.JSONDecodeError):
pass
return {}
outputs: dict with version and state keys, or empty dict on failure.
5. set up versioned migration chain
stamp save_version as an integer in every save from the first release (or retroactively call v1). write a pure function for each schema change (v -> v+1). store all migrations in a dict and never delete old ones. in load, apply migrations in order until the save version matches the current version.
godot:
const SAVE_VERSION := 3
var MIGRATIONS := {
1: func(d): d["flags"] = {k: true for k in d.pop("completed_quests", [])}, return d,
2: func(d): d.setdefault("difficulty", "normal"), return d,
}
func migrate_save(data: Dictionary) -> Dictionary:
var v = int(data.get("version", 1))
if v > SAVE_VERSION:
push_error("Save is from a newer build (v%d)" % v)
return {}
while v < SAVE_VERSION:
if MIGRATIONS.has(v):
data = MIGRATIONS[v].call(data)
v += 1
data["version"] = v
return data
python:
SAVE_VERSION = 3
def migrate_1_to_2(d):
d["flags"] = {k: True for k in d.pop("completed_quests", [])}
return d
def migrate_2_to_3(d):
d.setdefault("difficulty", "normal")
return d
MIGRATIONS = {1: migrate_1_to_2, 2: migrate_2_to_3}
def migrate_save(data):
v = int(data.get("version", 1))
if v > SAVE_VERSION:
raise ValueError(f"Save is from a newer build (v{v})")
while v < SAVE_VERSION:
if v in MIGRATIONS:
data = MIGRATIONS[v](data)
v += 1
data["version"] = v
return data
outputs: migrated data dict at current save_version.
6. apply state to game
write a function that takes the loaded dict and rebuilds game objects, nodes and positions from the data. do not store node paths or live references; always rebuild from ids and primitives.
outputs: game state synchronized to save data (player position set, inventory populated, flags applied, world seed set for procedural generation).
7. implement save slots
use a path template like user://save_%d.json for manual slots (0 through N). keep autosave in a separate file (user://autosave.json) so it never overwrites a manual slot.
outputs: slot files at save_0.json, save_1.json, etc., and autosave.json kept separate.
8. implement throttled autosave
call autosave at safe boundaries (after a checkpoint, level change, or quest completion), not mid-combat. throttle to at most once per minute using a cooldown timer. log each autosave so the player can see it happened.
godot:
var _autosave_cooldown := 0.0
func autosave_if_due(dt: float) -> void:
_autosave_cooldown -= dt
if _autosave_cooldown <= 0.0:
save_atomic(AUTOSAVE_PATH, capture_state())
_autosave_cooldown = 60.0
print("autosave written")
outputs: autosave.json updated at safe boundaries, no more than once per minute.
9. add input validation after migration
before applying the migrated save to the game, validate required keys exist and values are in legal ranges (hp between 0 and max_hp, positions within the world bounds, inventory item counts non-negative).
outputs: validated data dict or error message.
10. round-trip test (headless)
write a headless test that calls save_atomic twice (to test .bak fallback), simulates a truncated primary file, calls load_save and verifies it loads the .bak, then checks all loaded values match the original. run this test after every schema change.
godot headless:
# tools/save_roundtrip_test.gd
# godot --headless --path . --script res://tools/save_roundtrip_test.gd
extends SceneTree
const PATH := "user://test_save.json"
func _initialize() -> void:
var saver = load("res://save.gd").new()
var ok := true
var first := {"version": 3, "player": {"hp": 7, "pos": [1.5, -2.0]}, "flags": {"met_guard": true}}
var second := first.duplicate(true)
second["player"]["hp"] = 4
ok = ok and saver.save_atomic(PATH, first) == OK
ok = ok and saver.save_atomic(PATH, second) == OK
var loaded = saver.load_save(PATH)
ok = ok and loaded.get("version") is int and loaded["player"]["hp"] == 4
ok = ok and loaded["player"]["pos"] == [1.5, -2.0] and loaded["flags"] == second["flags"]
var f := FileAccess.open(PATH, FileAccess.WRITE)
f.store_string("{\"version\": 3, \"pla")
f.close()
ok = ok and saver.load_save(PATH)["player"]["hp"] == 7
for p in [PATH, PATH + ".bak", PATH + ".tmp"]:
DirAccess.remove_absolute(ProjectSettings.globalize_path(p))
print("SAVE_ROUNDTRIP ", "ok" if ok else "FAIL")
quit(0 if ok else 1)
outputs: test passes (SAVE_ROUNDTRIP ok) if primary and .bak recovery both work.
if the game is already shipped with saves: create a migration from the old schema to the new one and test it against real player saves in a fixtures folder. do not skip versions; apply each migration in order. if unsure of the original schema, ask players or audit the code.
if a save file is corrupt or missing: load the .bak instead. if both fail, return an empty dict and show the player a message. do not auto-create a new game state; ask them to load from an older save or start over.
if a loaded save is from a newer game version: refuse to load it with a clear error message. do not attempt to downgrade or strip unknown fields. the player must upgrade the game.
if autosave fires during combat or an unsafe moment: throttle it and defer to the next safe boundary (checkpoint, level transition). never save mid-action that could leave the game in an inconsistent state.
if disk is full or write permission is denied: catch the error, log it to the player, and do not try again immediately. offer to try again or fall back to the previous save.
if json.parse fails on a corrupt file: use the engine's json parser (json.parse() in godot, json.load() in python) to get the error line and message, so you can tell the player exactly where the corruption is. do not silently return an empty dict.
if a newer save version is encountered in MIGRATIONS.has() and the dict key is a float (godot json turns numbers to floats): convert with int(data["version"]) before the lookup, or use a string key.
if the game is multiplayer or cloud-synced (steam cloud): never use the client save as the authority for shared state. validate migrations and backup rotation per engine. for steam cloud, set up cross-platform sync in the steamworks app admin before shipping, and test file arrival on a second machine.
primary save file
{
"version": 3,
"player": {"hp": 50, "pos": [10.5, 20.0]},
"inventory": [{"id": "sword", "count": 1}],
"flags": {"met_guard": true, "killed_boss": false},
"seed": 12345
}
backup file
autosave file
slot files
round-trip test output
error log
the player can save and load a game
the .bak fallback works
autosave triggers at safe boundaries
migration works for old saves
newer saves are refused
round-trip test passes
no engine objects in the save
ask the player for a manual verification test
credits
original skill by gamedev-skills. enriched per implexa quality standards.