Load list from data to use throughout game

Godot Version

4

Question

I have a json file that I use to load data to create content. Right now I call the file and load it to find what I need each time I need it. I want to load it once in the beginning and use it through out the game. What is the best way to do this?

Disclaimer

I missed the fact that you’re working in GDScript. My reply is concerned with an approach in C#. Maybe you’ll still be able to extract something that will help you. Otherwise, hopefully someone else joins in on this as I don’t have any experience with GDScript.

Response

It really depends on how you store, structure and use your data as well as what type of data you are storing.

Assuming that you are loading and parsing your json save file into a Dictionary<string, Variant> (like seen here), you can simply store that in a variable that is easily accesible from all classes.

The sensible thing to do, if you haven’t already, is to create a static utility class/script for saving and loading your data. Inside this class you could make a static field that contains the latest loaded data. To simplify the interface with the utility class, you could add some simple logic in the Loading-function which returns the latest loaded data instead of reading/reloading the file based on some condition (e.g. if the application time is the same as that of the last load request).

Here’s an example:

private double lastLoadRequestMs;
private static Dictionary<string, Variant> lastLoadedData;
public static Dictionary<string, Variant> LoadGame()
{
    if (Time.GetTicksMsec() == lastLoadRequestMs)
    {
        return lastLoadedData;
    }
    else
    {
        // Load your data from the file
        // Store the loaded data in the static variable

        // Store the current load request time for later
        lastLoadRequestMs = Time.GetTicksMsec();
    }
}

As an aside, as long as you’re not reading and writing the file every frame, I don’t believe it’s that big of a deal to load a save file more than once. I sympathize with your urge to optimize though.

Thank you. I’m a C# guy, but went down the gdscript path to learn it. Right now, I store it in a gdscript array, which I have been told can be treated like a C# list. (not sure though). Your concept should work and I will give it a shot and see how it goes.

1 Like

Let me know how it goes!

went well!

1 Like