Hi,
i followed this guide https://coffeecoderblog.wordpress.com/2016/07/03/creating-a-save-system-in-godot/ to create a save/load system for my game. I managed to correctly save the data i wanted (i verified in the save file and the data is stored correctly), but i can't manage to correctly load the data.
The code seems correct to me but it returns this error when i run the program: "Invalid get index 'constrnumber' (on base: 'Dictionary')."
I copy my code here, hoping someone can kindly explain to me why it isn't working, or what am i doing wrong.
The line that generates the error is this one
constrnumber = currentLine["constrnumber"]
extends Node
# declare our variables
var constrnumber = 0
# initialize stuff here
func _ready():
# first determine if a Saves directory exists.
# if it doesn't, create it.
var dir = Directory.new()
if !dir.dir_exists("user://Saves"):
dir.open("user://")
dir.make_dir("user://Saves")
# the following functions are getters and setters for the variables
# get the construction number
func get_constrnumber():
return constrnumber
# set the construction number
func set_constrnumber(var amount):
constrnumber += amount
# the following functions save and load a game, depending on what the player does at the main/pause menus.
# at the end of each level, the save function is automatically called.
# first create a dictionary to store the save info in. Similar to a serializable class in Unity in which
# the player data would be stored.
var GameData = {
"constrnumber":0
}
# this saves the current game state
func save_game_state(var saveName):
# create a file object
var saveGame = File.new()
saveGame.open("user://Saves/"+saveName+".save", File.WRITE)
# create a data object to store the current save data in
var data = GameData
# store the data
data.constrnumber = get_constrnumber()
# write the data to disk
#saveGame.store_line(data.to_json())
saveGame.store_line(to_json(data))
saveGame.close()
# this loads a previously saved game state
func load_game_state(var saveName):
# create a file object
var loadGame = File.new()
# see if the file actually exists before opening it
if !loadGame.file_exists("user://Saves/"+saveName+".save"):
print ("File not found! Aborting...")
return
# use an empty dictionary to assign temporary data to
var currentLine = {}
# read the data in
loadGame.open("user://Saves/"+saveName+".save", File.READ)
while(!loadGame.eof_reached()):
# use currentLine to parse through the file
#currentLine.parse_json(loadGame.get_line())
#loadGame.get_line(parse_json(line))
#warning-ignore:unused_variable
var current_line = parse_json(loadGame.get_line())
# assign the data to the variables
constrnumber = currentLine["constrnumber"]
loadGame.close()
Thank you all.