Saving games

    Note

    If you’re looking to save user configuration, you can use the class for this purpose.

    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 Scripting (continued) 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:

    C#

    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 and parse_json(), 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 Godot.Collections.Dictionary<string, object> Save()
    2. {
    3. return new Godot.Collections.Dictionary<string, 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. { "LastAttack", LastAttack }
    23. };
    24. }

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

    As covered in the tutorial, we’ll need to open a file so we can write to it or read from it. Now that we have a way to call our groups and get their relevant data, let’s use to_json() 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. // Note: This can be called from anywhere inside the tree. This function is
    2. // path independent.
    3. // dict of relevant variables.
    4. public void SaveGame()
    5. {
    6. saveGame.Open("user://savegame.save", (int)File.ModeFlags.Write);
    7. var saveNodes = GetTree().GetNodesInGroup("Persist");
    8. foreach (Node saveNode in saveNodes)
    9. {
    10. // Check the node is an instanced scene so it can be instanced again during load.
    11. if (saveNode.Filename.Empty())
    12. {
    13. GD.Print(String.Format("persistent node '{0}' is not an instanced scene, skipped", saveNode.Name));
    14. continue;
    15. }
    16. // Check the node has a save function.
    17. if (!saveNode.HasMethod("Save"))
    18. {
    19. GD.Print(String.Format("persistent node '{0}' is missing a Save() function, skipped", saveNode.Name));
    20. continue;
    21. }
    22. // Call the node's save function.
    23. var nodeData = saveNode.Call("Save");
    24. // Store the save dictionary as a new line in the save file.
    25. saveGame.StoreLine(JSON.Print(nodeData));
    26. }
    27. saveGame.Close();
    28. }

    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. if (!saveGame.FileExists("user://savegame.save"))
    6. return; // Error! We don't have a save to load.
    7. // We need to revert the game state so we're not cloning objects during loading.
    8. // This will vary wildly depending on the needs of a project, so take care with
    9. // this step.
    10. // For our example, we will accomplish this by deleting saveable objects.
    11. var saveNodes = GetTree().GetNodesInGroup("Persist");
    12. foreach (Node saveNode in saveNodes)
    13. saveNode.QueueFree();
    14. // Load the file line by line and process that dictionary to restore the object
    15. // it represents.
    16. saveGame.Open("user://savegame.save", (int)File.ModeFlags.Read);
    17. while (saveGame.GetPosition() < saveGame.GetLen())
    18. {
    19. // Get the saved dictionary from the next line in the save file
    20. var nodeData = new Godot.Collections.Dictionary<string, object>((Godot.Collections.Dictionary)JSON.Parse(saveGame.GetLine()).Result);
    21. // Firstly, we need to create the object and add it to the tree and set its position.
    22. var newObjectScene = (PackedScene)ResourceLoader.Load(nodeData["Filename"].ToString());
    23. var newObject = (Node)newObjectScene.Instance();
    24. GetNode(nodeData["Parent"].ToString()).AddChild(newObject);
    25. newObject.Set("Position", new Vector2((float)nodeData["PosX"], (float)nodeData["PosY"]));
    26. // Now we set the remaining variables.
    27. foreach (KeyValuePair<object, object> entry in nodeData)
    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. }
    35. }

    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.

    We have glossed over setting up the game state for loading. It’s ultimately up to the project creator where much of this logic goes. This is often complicated and will need to be heavily customized based on the needs of the individual project.