Saving: FileAccess, ConfigFile & JSON
Games save two kinds of data: settings (volume, key bindings, fullscreen) and progress (level, inventory, position). Godot gives you three tools:
| Tool | Format | Best for |
|---|---|---|
ConfigFile |
INI-like text with [sections] and key=value |
settings |
FileAccess + JSON |
JSON text | progress you want to read, diff or edit by hand; data shared with other tools |
FileAccess.store_var / get_var |
Godot's binary Variant format | progress with Godot types (Vector2, Color) and no conversion code |
Saving whole resources with ResourceSaver is a fourth option, covered in Resources & .tres Files. Be careful with it for save games: a .tres file can reference scripts, so loading a resource file a player downloaded can run code. JSON, ConfigFile and get_var (with objects disabled, the default) only produce data.
user:// and res://
res://is the project folder. In an exported game it is read-only (packed into the.pck).user://is a per-user writable folder: on Windows%APPDATA%\Godot\app_userdata\<project name>, on Linux~/.local/share/godot/app_userdata/<project name>, on macOS~/Library/Application Support/Godot/app_userdata/<project name>. In the editor, Project > Open User Data Folder opens it. Enable Project Settings > Application > Config > Use Custom User Dir to get a cleaner folder name.
Always save to user://. Writing into res:// works in the editor and silently fails after export.
JSON with FileAccess
extends SceneTree
const SAVE_PATH := "user://save.json"
func _init():
print("exists before: ", FileAccess.file_exists(SAVE_PATH))
var data := {
"version": 1,
"level": 3,
"coins": 42,
"position": [120.5, 64.0],
"unlocked": ["double_jump"],
}
var f := FileAccess.open(SAVE_PATH, FileAccess.WRITE)
f.store_string(JSON.stringify(data, " "))
f.close()
print("exists after: ", FileAccess.file_exists(SAVE_PATH))
print(FileAccess.get_file_as_string(SAVE_PATH))
var loaded = JSON.parse_string(FileAccess.get_file_as_string(SAVE_PATH))
print("level = ", loaded.level, " (", type_string(typeof(loaded.level)), ")")
var level: int = int(loaded.level)
var pos := Vector2(loaded.position[0], loaded.position[1])
print("as int: ", level, ", position: ", pos)
quit()exists before: false
exists after: true
{
"coins": 42,
"level": 3,
"position": [
120.5,
64.0
],
"unlocked": [
"double_jump"
],
"version": 1
}
level = 3.0 (float)
as int: 3, position: (120.5, 64.0)
Three things every Godot developer trips over:
- JSON numbers come back as
float. JSON has a single number type, so3loads as3.0. Convert withint()before using a value as an index, a level number or amatchcase, or comparisons such astypeof(x) == TYPE_INTfail. - Godot types don't survive.
JSON.stringify(Vector2(1, 2))produces the string"(1, 2)", not something you can load. Store vectors and colours as arrays or dictionaries and rebuild them (as withpositionabove).JSON.from_native()/to_native()(Godot 4.4+) can encode Godot types too, in a Godot-specific JSON shape. - Keys are sorted by
JSON.stringifyby default (itssort_keysargument), which is nice for diffs.
FileAccess.open returns null on failure; check it and read FileAccess.get_open_error(). A FileAccess closes itself when the last reference goes away, but call close() when you are going to read the same file right after writing it.
Binary Variants, ConfigFile and DirAccess
extends SceneTree
func _init():
var json := JSON.new()
var err := json.parse("{\"coins\": 42, \"level\" 3}")
print(error_string(err), " at line ", json.get_error_line(), ": ", json.get_error_message())
# Binary: store_var keeps Godot types
var f := FileAccess.open("user://save.bin", FileAccess.WRITE)
f.store_var({"pos": Vector2(120.5, 64), "level": 3, "color": Color.GOLD})
f.close()
f = FileAccess.open("user://save.bin", FileAccess.READ)
var d: Dictionary = f.get_var()
f.close()
print(d.pos, " ", type_string(typeof(d.pos)), ", level ", type_string(typeof(d.level)))
# Settings with ConfigFile
var cfg := ConfigFile.new()
cfg.set_value("audio", "music", 0.8)
cfg.set_value("audio", "sfx", 1.0)
cfg.set_value("video", "fullscreen", true)
cfg.set_value("controls", "jump", "Space")
print(error_string(cfg.save("user://settings.cfg")))
print(FileAccess.get_file_as_string("user://settings.cfg"))
var c2 := ConfigFile.new()
var e2 := c2.load("user://settings.cfg")
print(error_string(e2), " music=", c2.get_value("audio", "music", 1.0), " vsync=", c2.get_value("video", "vsync", true))
print(c2.get_sections(), " ", c2.get_section_keys("audio"))
print(error_string(ConfigFile.new().load("user://nope.cfg")))
# Save slots in a folder
DirAccess.make_dir_recursive_absolute("user://saves")
for i in 3:
var s := FileAccess.open("user://saves/slot_%d.json" % i, FileAccess.WRITE)
s.store_string("{}")
s.close()
print(DirAccess.get_files_at("user://saves"))
print(error_string(DirAccess.remove_absolute("user://saves/slot_1.json")))
print(DirAccess.get_files_at("user://saves"))
var r := FileAccess.open("user://missing.json", FileAccess.READ)
print(r == null, " ", error_string(FileAccess.get_open_error()))
quit()Parse error at line 0: Expected ':'
(120.5, 64.0) Vector2, level int
OK
[audio]
music=0.8
sfx=1.0
[video]
fullscreen=true
[controls]
jump="Space"
OK music=0.8 vsync=true
["audio", "video", "controls"] ["music", "sfx"]
File not found
["slot_0.json", "slot_1.json", "slot_2.json"]
OK
["slot_0.json", "slot_2.json"]
true File not found
- Use a
JSONinstance (not the staticparse_string) when you want an error message for a broken file;parse_stringjust returnsnulland prints an engine error. store_varkeepsVector2andintexactly. The price: the file is binary and Godot-specific. Never passtrueforallow_objectstoget_varon files players can swap, for the same reason as.tresfiles.ConfigFile.get_value(section, key, default)returns the default for missing keys, so adding a new setting in an update needs no migration. Its values are Godot-typed text (Color(...),Vector2(...)work too).- Error codes are
Errorenum values;error_string()turns them into text for logs.
A robust save system
Real save code has to survive a crash halfway through writing, a missing file, a corrupted file and save files from older versions of your game:
extends SceneTree
const PATH := "user://save.json"
const VERSION := 2
const DEFAULTS := {"version": VERSION, "level": 1, "coins": 0, "volume": 1.0, "hats": []}
func save_game(data: Dictionary) -> Error:
var tmp := PATH + ".tmp"
var f := FileAccess.open(tmp, FileAccess.WRITE)
if f == null:
return FileAccess.get_open_error()
f.store_string(JSON.stringify(data))
f.close()
return DirAccess.rename_absolute(tmp, PATH) # replace the old file only after a full write
func load_game() -> Dictionary:
if not FileAccess.file_exists(PATH):
return DEFAULTS.duplicate(true)
var parsed = JSON.parse_string(FileAccess.get_file_as_string(PATH))
if typeof(parsed) != TYPE_DICTIONARY:
push_warning("save file unreadable, starting fresh")
return DEFAULTS.duplicate(true)
return migrate(parsed)
func migrate(d: Dictionary) -> Dictionary:
var v := int(d.get("version", 1))
if v < 2:
d["coins"] = d.get("gold", 0) # v1 called coins "gold"
d.erase("gold")
var out := DEFAULTS.duplicate(true)
out.merge(d, true) # saved values win, new keys get defaults
out.version = VERSION
out.level = int(out.level)
out.coins = int(out.coins)
return out
func _init():
print("fresh: ", load_game())
var old := FileAccess.open(PATH, FileAccess.WRITE)
old.store_string('{"version": 1, "level": 4, "gold": 250}')
old.close()
var d := load_game()
print("migrated: ", d)
d.hats.append("crown")
print("save: ", error_string(save_game(d)))
print("file: ", FileAccess.get_file_as_string(PATH))
quit()fresh: { "version": 2, "level": 1, "coins": 0, "volume": 1.0, "hats": [] }
migrated: { "version": 2, "level": 4, "coins": 250, "volume": 1.0, "hats": [] }
save: OK
file: {"coins":250,"hats":["crown"],"level":4,"version":2,"volume":1.0}
The pattern:
- Write to a temporary file, then rename.
DirAccess.renameoverwrites the destination, so a crash during the write leaves the old save intact instead of a half-written one. - A
versionfield from day one, and amigrate()step that upgrades old files. Players keep save files across many updates. - Defaults merged under the saved data (
merge(d, true)lets saved values overwrite), so new fields appear with sensible values. duplicate(true)on the defaults: aconstdictionary is read-only, and a shallow copy would share the innerhatsarray between saves.
In a game, put save_game/load_game in an autoload (SaveManager) and let each saveable node contribute its own dictionary, for example by calling a save_state() method on every node in a "persist" group (Groups & Tree Queries).
Note: On the web,
user://is stored in the browser's IndexedDB; it persists, but players can clear it. On mobile it lives in the app's private storage and is removed when the app is uninstalled.
Test yourself
You save {"level": 3} with JSON.stringify and load it back. What is typeof(data.level)?
TYPE_INTTYPE_FLOAT, because JSON has a single number typeTYPE_STRINGTYPE_NIL
Why should save files go to user:// rather than res://?
user://is fasterres://is read-only in exported games;user://is the writable per-user data folderres://is deleted on every run- Only
user://supports JSON
What does writing to save.json.tmp and then renaming it to save.json protect against?
- Cheating
- A crash or power loss in the middle of a write corrupting the only save file
- Slow disks
- JSON number conversion