Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 ยท Projects and Practice

Project: A Save and Load System

Build a robust save system in Godot 4: the user:// path, JSON and ConfigFile saves, custom Resources, save groups, versioning and migration, atomic writes and checksums, with Python stand-ins.

A game that forgets its players' progress is frustrating. Saving is simple in principle (turn state into data, write a file) but easy to get wrong: files can be corrupted, formats change between versions, and cheaters edit them. This project builds a small, reliable save system you can drop into any Godot game, using ideas you can reuse in the platformer or shooter.

Godot cannot run on this site, so GDScript is read-only. The Python blocks are stand-ins that perform the same data steps (serialization, versioning, atomic writes, checksums) so you can run and change them.

Where to save: user://

Never write to res:// in an exported game: it is read-only (inside the PCK). Use user://, a per-project folder that Godot maps to a safe place on every platform (for example %APPDATA%\Godot\app_userdata\<project> on Windows). On the web, user:// is stored in the browser's IndexedDB. Find the real path with OS.get_user_data_dir() or Project > Open User Data Folder.

Three formats

  • ConfigFile: INI-style sections and keys; ideal for settings (volume, key bindings).
  • JSON: readable, easy to debug and to migrate; the best default for save games.
  • Custom Resource (.tres/.res) or var_to_bytes: stores Godot types such as Vector2 and Color directly. Never load a Resource file from an untrusted source, because it can contain scripts that run.

JSON cannot store Vector2 or Color, so convert them to arrays or dictionaries.

GDSCRIPT
# autoload/save_manager.gd
extends Node

const SAVE_PATH := "user://save.json"
const SAVE_VERSION := 2

func save_game(data: Dictionary) -> bool:
	data["version"] = SAVE_VERSION
	var text := JSON.stringify(data, "\t")
	var tmp_path := SAVE_PATH + ".tmp"
	var file := FileAccess.open(tmp_path, FileAccess.WRITE)
	if file == null:
		push_error("Cannot save: %s" % error_string(FileAccess.get_open_error()))
		return false
	file.store_string(text)
	file.close()
	DirAccess.rename_absolute(tmp_path, SAVE_PATH)     # swap only after a full write
	return true

func load_game() -> Dictionary:
	if not FileAccess.file_exists(SAVE_PATH):
		return {}
	var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(SAVE_PATH))
	if typeof(parsed) != TYPE_DICTIONARY:
		push_warning("Save file is corrupt")
		return {}
	return migrate(parsed)

JSON.parse_string() returns null when the text is not valid JSON, so always check the type.

Python Stand-in (Python, not Godot): serialize game state, converting special types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Atomic writes

If the game crashes (or the battery dies) while writing the save file, you lose the player's progress. The fix is an atomic write: write to a temporary file, then rename it over the real one. A rename is all-or-nothing, so the player always has either the old complete file or the new complete file. Keep one backup (save.json.bak) of the previous good save for extra safety.

Python Stand-in (Python, not Godot): atomic write survives a crash mid-save

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Saving the scene: the persist group

Rather than one script that knows about every object, let each saveable node describe itself. Add saveable nodes to a group persist and give them save() and load_state() methods.

GDSCRIPT
# in any saveable node, e.g. a chest
func save() -> Dictionary:
	return {"path": scene_file_path, "pos": [position.x, position.y], "opened": opened}

func load_state(d: Dictionary) -> void:
	position = Vector2(d.pos[0], d.pos[1])
	opened = d.opened

# in SaveManager
func collect_state() -> Dictionary:
	var objects: Array = []
	for node in get_tree().get_nodes_in_group("persist"):
		if node.scene_file_path.is_empty():
			continue                         # only scenes can be re-created
		objects.append(node.save())
	return {"objects": objects, "score": GameState.score, "level": get_tree().current_scene.scene_file_path}

To load: change to the saved level scene, clear old persist objects, instantiate each saved scene and call load_state(d). Do not store node references or whole nodes; store plain data (paths, numbers, flags).

Versioning and migration

Your save format will change. Store a version number and write a small migration function that upgrades old files step by step. Never delete migration steps: someone always has a very old save.

GDSCRIPT
func migrate(data: Dictionary) -> Dictionary:
	var v: int = data.get("version", 1)
	if v < 2:
		data["inventory"] = data.get("items", [])     # v1 called it "items"
		data.erase("items")
	data["version"] = SAVE_VERSION
	return data
Python Stand-in (Python, not Godot): chain migrations from any old version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Integrity, cheating and privacy

A checksum detects accidental corruption: store a hash of the data and compare on load. It does not stop a determined cheater (they can recompute it); for competitive games keep the authority on a server. Do not save secrets or personal data in plain text. For optional protection FileAccess.open_encrypted_with_pass() encrypts a file, though a key embedded in your game can still be extracted.

Python Stand-in (Python, not Godot): detect a corrupted or edited save with a hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Autosave, slots and settings

Offer 3 slots (user://save_1.json ...) and show their metadata (level name, play time, screenshot) in a menu without loading everything. Autosave at checkpoints and on NOTIFICATION_WM_CLOSE_REQUEST, but not every frame. Keep settings in user://settings.cfg with a ConfigFile so a player can reset game progress without losing their volume and key bindings.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should an exported game write save files?

    res:// is read-only in exports; user:// is a writable per-project folder on every platform.
  2. 2. Why write to a temporary file and rename it?

    A rename swaps the file all at once, so the real save is never half-written.
  3. 3. What is a save version number for?

    With a version stored, load code can apply the missing migration steps.
  4. 4. Why is loading a .tres Resource from a user-shared save risky?

    Prefer plain JSON for data that may come from untrusted sources.

Summary

  • Save under user://; use JSON for saves, ConfigFile for settings.
  • Convert Godot types to plain data; let nodes in a persist group describe themselves.
  • Write atomically, keep a backup, check types when loading.
  • Store a version and migrate step by step; use hashes for corruption detection, not security.

Next: Godot Practice Challenges