Last active
July 9, 2020 22:30
-
-
Save brunosxs/27d5aefadcb9c9ce2ec5a12a31995168 to your computer and use it in GitHub Desktop.
Godot Quick Tips 02: Simple save and load methods for godot engine with dir and file handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment