Saving games

    Firstly, we should identify what objects we want to keep between game sessions and what information we want to keep from those objects. For this tutorial, we will use groups to mark and handle objects to be saved, but other methods are certainly possible.

    We will start by adding objects we wish to save to the “Persist” group. As in the tutorial, we can do this through either the GUI or script. Let’s add the relevant nodes using the GUI:

    Once this is done, when we need to save the game, we can get all objects to save them and then tell them all to save with this script:

    GDScript

    1. foreach (Node saveNode in saveNodes)
    2. {
    3. // Now, we can call our save function on each node.
    4. }

    The next step is to serialize the data. This makes it much easier to read from and store to disk. In this case, we’re assuming each member of group Persist is an instanced node and thus has a path. GDScript has helper functions for this, such as to_json() and , so we will use a dictionary. Our node needs to contain a save function that returns this data. The save function will look like this:

    GDScript

    C#

    1. public Dictionary<object, object> Save()
    2. {
    3. return new Dictionary<object, object>()
    4. {
    5. { "Filename", GetFilename() },
    6. { "Parent", GetParent().GetPath() },
    7. { "PosX", Position.x }, // Vector2 is not supported by JSON
    8. { "PosY", Position.y },
    9. { "Attack", Attack },
    10. { "Defense", Defense },
    11. { "CurrentHealth", CurrentHealth },
    12. { "MaxHealth", MaxHealth },
    13. { "Damage", Damage },
    14. { "Regen", Regen },
    15. { "Experience", Experience },
    16. { "Tnl", Tnl },
    17. { "Level", Level },
    18. { "AttackGrowth", AttackGrowth },
    19. { "DefenseGrowth", DefenseGrowth },
    20. { "HealthGrowth", HealthGrowth },
    21. { "IsAlive", IsAlive },
    22. };
    23. }

    This gives us a dictionary with the style { "variable_name":value_of_variable }, which will be useful when loading.

    As covered in the File system tutorial, we’ll need to open a file and write to it and then later, read from it. Now that we have a way to call our groups and get their relevant data, let’s use to convert it into an easily stored string and store them in a file. Doing it this way ensures that each line is its own object, so we have an easy way to pull the data out of the file as well.

    C#

    1. // path independent.
    2. // Go through everything in the persist category and ask them to return a
    3. // dict of relevant variables
    4. public void SaveGame()
    5. {
    6. var saveGame = new File();
    7. saveGame.Open("user://savegame.save", (int)File.ModeFlags.Write);
    8. var saveNodes = GetTree().GetNodesInGroup("Persist");
    9. foreach (Node saveNode in saveNodes)
    10. {
    11. var nodeData = saveNode.Call("Save");
    12. saveGame.StoreLine(JSON.Print(nodeData));
    13. }
    14. saveGame.Close();
    15. }

    Game saved! Loading is fairly simple as well. For that, we’ll read each line, use parse_json() to read it back to a dict, and then iterate over the dict to read our values. But we’ll need to first create the object and we can use the filename and parent values to achieve that. Here is our load function:

    GDScript

    C#

    1. // Note: This can be called from anywhere inside the tree. This function is
    2. // path independent.
    3. public void LoadGame()
    4. {
    5. var saveGame = new File();
    6. if (!saveGame.FileExists("user://savegame.save"))
    7. return; // Error! We don't have a save to load.
    8. // We need to revert the game state so we're not cloning objects during loading.
    9. // This will vary wildly depending on the needs of a project, so take care with
    10. // this step.
    11. foreach (Node saveNode in saveNodes)
    12. saveNode.QueueFree();
    13. // Load the file line by line and process that dictionary to restore the object
    14. // it represents.
    15. saveGame.Open("user://savegame.save", (int)File.ModeFlags.Read);
    16. while (!saveGame.EofReached())
    17. {
    18. var currentLine = (Dictionary<object, object>)JSON.Parse(saveGame.GetLine()).Result;
    19. if (currentLine == null)
    20. continue;
    21. // Firstly, we need to create the object and add it to the tree and set its position.
    22. var newObjectScene = (PackedScene)ResourceLoader.Load(currentLine["Filename"].ToString());
    23. var newObject = (Node)newObjectScene.Instance();
    24. GetNode(currentLine["Parent"].ToString()).AddChild(newObject);
    25. newObject.Set("Position", new Vector2((float)currentLine["PosX"], (float)currentLine["PosY"]));
    26. // Now we set the remaining variables.
    27. foreach (KeyValuePair<object, object> entry in currentLine)
    28. {
    29. string key = entry.Key.ToString();
    30. if (key == "Filename" || key == "Parent" || key == "PosX" || key == "PosY")
    31. continue;
    32. newObject.Set(key, entry.Value);
    33. }
    34. }

    And now, we can save and load an arbitrary number of objects laid out almost anywhere across the scene tree! Each object can store different data depending on what it needs to save.

    This implementation assumes no Persist objects are children of other Persist objects. Otherwise, invalid paths would be created. To accommodate nested Persist objects, consider saving objects in stages. Load parent objects first so they are available for the add_child() call when child objects are loaded. You will also need a way to link children to parents as the will likely be invalid.