Search code examples
saveloadgodotgdscript

(Godot) Saving multiple keys and reloading them


I'm kind of stumped. I've followed and adapted the save system from this.

To phrase the problem, I'm unsure how to load the dictionaries back into the original variables. Most likely easier to explain the problem as you see it.

# This would be "GlobalData"
onready var KEY = name

# Stats dictionary
var stats:= {
    "health" : 75,
    "stamina": 25
}

# Meta Dictionary
var meta:= {
    "testing": "I'm a totally random thing",
    "testing2": 2002,
    "date": "Thursday, 2020-08-20, 20:12"
}

# Load both into array to iterate through upon saving
var list = [stats, meta]

func save(save_game:Resource):
    var i = 0
    for element in list:
        
        # Make a unique key based on iteration
        var temp:String = KEY + String(i)
        
        # Store data to key
        save_game.data[temp] = element
        i = i+1
        

func load(save_game:Resource):
    var i = 0
    
    # === Where the error lies === #
    # While saving works fine, I cannot use the list array to push content back into the original dictionaries
    # If I targeted the dictionary by it's variable, then it got applied.

    for element in list:
        var temp:String = KEY + String(i)
        element = save_game.data[temp]
        i = i+1


So, my question relies in "how do I re-apply the loaded data?". Do I have to write the list into a way, that it would store the dictionary name too? Or is it possible to somehow call the name of the element to get it to target the original variable/dictionary?

PS. Don't ask why I'm not using i++ or i+=1. Errors out.


Solution

  • The KEY value, as used by GDQuest in that video, identifies the node on which the save/load methods are called, not every piece of data you save individually.

    You have many options to achieve what you want. This are two simple ones:

    1 - More in line with what the video is doing: create a dictionary to contain all your separate information, and store that under the node unique key.

    ...
    func save(save_game:Resource):
        var node_data = {
            stats = stats,
            meta = meta,
        }
        
        save_game.data[KEY] = node_data
      
    func load(save_game:Resource):
        stats = save_game.data[KEY].stats
    
    
        meta = save_game.data[KEY].meta
    

    2 - More in line with what you are trying to do: create unique fixed keys for each dictionary/element you are storing, and use that to save/load them.

    onready var KEY_STATS = name + "_stats" 
    onready var KEY_META = name  + "_meta"
    ...
    
    func save(save_game:Resource):
        save_game.data[KEY_STATS] = stats
        save_game.data[KEY_META] = meta
      
    func load(save_game:Resource):
        meta = save_game.data[KEY_STATS]
        stats = save_game.data[KEY_META]