Godot Engine Quick Tips - 02: Simple save and load methods for godot engine with dir and file handling

BrunoSXS published on
3 min, 414 words

Now I share with you guys how I handle save files in games. It is a pretty simple script that... well, works.
Godot also has a ConfigFile class that can be used for it, but I preffer to work with dictionaries because my code ends simpler.

With basically 3 variables
default_save
current_save_game
save_slot

The basic idea is: This file is a singleton and uses current_save_game to store the info we want to use in our game. At the start of the game, it tries to load the desired save file based on the save_slot. If it doesn't exist, it creates one with the contents of another var called default_save

Created by BrunoSXS

LICENSED UNDER MIT

var save_slot = 0 # Just like classic JRPs, change the slot to save in a different place
var current_save_game # This is the contents of the save file, for now we just declare it
var default_save = {"money":0,"powers":null} # The default save contents, if there is no save file to load, then, the current_save_game gets its contents from this variable and then creates a save file with it


func _ready():
	current_save_game = load_game(save_slot) if typeof(load_game(save_slot)) == TYPE_DICTIONARY else default_save # This is the first loading, when the game starts.

func load_game(save_slot): # I used the concept of save slots to handle multiple saves, use what suits you.
	var F = File.new() # We initialize the File class
	var D = Directory.new() # and the Directory class
	if D.dir_exists("user://save"): # Check if the folder 'save' exists before moving on
		if F.open(str("user://save/",save_slot,".save"), File.READ_WRITE) == OK: # If the opening of the save file returns OK
			var temp_d # we create a temporary var to hold the contents of the save file
			temp_d = F.get_var() # we get the contents of the save file and store it on TEMP_D
			return temp_d # we return it to do our thing
		else: # In case the opening of the save file doesn't give an OK, we create a save file
			print("save file doesn't exist, creating one") 
			save_game(save_slot) 
	else: # If the folder doesn't exist, we create one...
		D.make_dir("user://save")
		save_game(save_slot) # and we create the save file using the save_game function

func save_game(save_slot): # This functions save the contents of current_save_game variable into a file 
	var F = File.new()
	F.open(str("user://save/",save_slot,".save"), File.READ_WRITE) # we open the file
	F.store_var(current_save_game) # then we store the contents of the var save inside it
	F.close() # and we gracefully close the file :)