The documentation explain both how to read and write data and how to use it in a way it restores the game to its previous state.
Here is a simplified example on how to save and load variables in a file:
(This was in Godot 2.1, but it's not much different in 3.1, use to_json(data)
instead of data.to_json()
)
Save variables
# Construct a dictionary with whatever data you want
var data = {
player_level = 42,
last_item = "sword"
}
# Open a file
var file = File.new()
if file.open("user://saved_game.sav", File.WRITE) != 0:
print("Error opening file")
return
# Save the dictionary as JSON (or whatever you want, JSON is convenient here because it's built-in)
file.store_line(data.to_json())
file.close()
Load variables
# Check if there is a saved file
var file = File.new()
if not file.file_exists("user://saved_game.sav"):
print("No file saved!")
return
# Open existing file
if file.open("user://saved_game.sav", File.READ) != 0:
print("Error opening file")
return
# Get the data
var data = {}
data.parse_json(file.get_line())
# Then do what you want with the data
The path begins with "user://" so it targets a standard writable folder in the home of the user no matter which platform/OS the game runs on. For example on Windows it's "AppData/Local/Godot/..."