Up to date

This page is up to date for Godot 4.1. If you still find outdated information, please open an issue.

Saving games

Introduction

Save games can be complicated. For example, it may be desirable to store information from multiple objects across multiple levels. Advanced save game systems should allow for additional information about an arbitrary number of objects. This will allow the save function to scale as the game grows more complex.

Note

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

See also

You can see how saving and loading works in action using the Saving and Loading (Serialization) demo project.

Identify persistent objects

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. We can do this through either the GUI or script. Let’s add the relevant nodes using the GUI:

../../_images/groups.png

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:

GDScriptC#

  1. var save_nodes = get_tree().get_nodes_in_group("Persist")
  2. for i in save_nodes:
  3. # Now, we can call our save function on each node.
  1. var saveNodes = GetTree().GetNodesInGroup("Persist");
  2. foreach (Node saveNode in saveNodes)
  3. {
  4. // Now, we can call our save function on each node.
  5. }

Serializing

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 class JSON to convert between dictionary and string, Our node needs to contain a save function that returns this data. The save function will look like this:

GDScriptC#

  1. func save():
  2. var save_dict = {
  3. "filename" : get_scene_file_path(),
  4. "parent" : get_parent().get_path(),
  5. "pos_x" : position.x, # Vector2 is not supported by JSON
  6. "pos_y" : position.y,
  7. "attack" : attack,
  8. "defense" : defense,
  9. "current_health" : current_health,
  10. "max_health" : max_health,
  11. "damage" : damage,
  12. "regen" : regen,
  13. "experience" : experience,
  14. "tnl" : tnl,
  15. "level" : level,
  16. "attack_growth" : attack_growth,
  17. "defense_growth" : defense_growth,
  18. "health_growth" : health_growth,
  19. "is_alive" : is_alive,
  20. "last_attack" : last_attack
  21. }
  22. return save_dict
  1. public Godot.Collections.Dictionary<string, Variant> Save()
  2. {
  3. return new Godot.Collections.Dictionary<string, Variant>()
  4. {
  5. { "Filename", SceneFilePath },
  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.

Saving and reading data

As covered in the File system 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 the class 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.

GDScriptC#

  1. # Note: This can be called from anywhere inside the tree. This function is
  2. # path independent.
  3. # Go through everything in the persist category and ask them to return a
  4. # dict of relevant variables.
  5. func save_game():
  6. var save_game = FileAccess.open("user://savegame.save", FileAccess.WRITE)
  7. var save_nodes = get_tree().get_nodes_in_group("Persist")
  8. for node in save_nodes:
  9. # Check the node is an instanced scene so it can be instanced again during load.
  10. if node.scene_file_path.is_empty():
  11. print("persistent node '%s' is not an instanced scene, skipped" % node.name)
  12. continue
  13. # Check the node has a save function.
  14. if !node.has_method("save"):
  15. print("persistent node '%s' is missing a save() function, skipped" % node.name)
  16. continue
  17. # Call the node's save function.
  18. var node_data = node.call("save")
  19. # JSON provides a static method to serialized JSON string.
  20. var json_string = JSON.stringify(node_data)
  21. # Store the save dictionary as a new line in the save file.
  22. save_game.store_line(json_string)
  1. // Note: This can be called from anywhere inside the tree. This function is
  2. // path independent.
  3. // Go through everything in the persist category and ask them to return a
  4. // dict of relevant variables.
  5. public void SaveGame()
  6. {
  7. using var saveGame = FileAccess.Open("user://savegame.save", FileAccess.ModeFlags.Write);
  8. var saveNodes = GetTree().GetNodesInGroup("Persist");
  9. foreach (Node saveNode in saveNodes)
  10. {
  11. // Check the node is an instanced scene so it can be instanced again during load.
  12. if (string.IsNullOrEmpty(saveNode.SceneFilePath))
  13. {
  14. GD.Print($"persistent node '{saveNode.Name}' is not an instanced scene, skipped");
  15. continue;
  16. }
  17. // Check the node has a save function.
  18. if (!saveNode.HasMethod("Save"))
  19. {
  20. GD.Print($"persistent node '{saveNode.Name}' is missing a Save() function, skipped");
  21. continue;
  22. }
  23. // Call the node's save function.
  24. var nodeData = saveNode.Call("Save");
  25. // Json provides a static method to serialized JSON string.
  26. var jsonString = Json.Stringify(nodeData);
  27. // Store the save dictionary as a new line in the save file.
  28. saveGame.StoreLine(jsonString);
  29. }
  30. }

Game saved! Now, to load, we’ll read each line. Use the parse method to read the JSON string back to a dictionary, 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:

GDScriptC#

  1. # Note: This can be called from anywhere inside the tree. This function
  2. # is path independent.
  3. func load_game():
  4. if not FileAccess.file_exists("user://savegame.save"):
  5. return # Error! We don't have a save to load.
  6. # We need to revert the game state so we're not cloning objects
  7. # during loading. This will vary wildly depending on the needs of a
  8. # project, so take care with this step.
  9. # For our example, we will accomplish this by deleting saveable objects.
  10. var save_nodes = get_tree().get_nodes_in_group("Persist")
  11. for i in save_nodes:
  12. i.queue_free()
  13. # Load the file line by line and process that dictionary to restore
  14. # the object it represents.
  15. var save_game = FileAccess.open("user://savegame.save", FileAccess.READ)
  16. while save_game.get_position() < save_game.get_length():
  17. var json_string = save_game.get_line()
  18. # Creates the helper class to interact with JSON
  19. var json = JSON.new()
  20. # Check if there is any error while parsing the JSON string, skip in case of failure
  21. var parse_result = json.parse(json_string)
  22. if not parse_result == OK:
  23. print("JSON Parse Error: ", json.get_error_message(), " in ", json_string, " at line ", json.get_error_line())
  24. continue
  25. # Get the data from the JSON object
  26. var node_data = json.get_data()
  27. # Firstly, we need to create the object and add it to the tree and set its position.
  28. var new_object = load(node_data["filename"]).instantiate()
  29. get_node(node_data["parent"]).add_child(new_object)
  30. new_object.position = Vector2(node_data["pos_x"], node_data["pos_y"])
  31. # Now we set the remaining variables.
  32. for i in node_data.keys():
  33. if i == "filename" or i == "parent" or i == "pos_x" or i == "pos_y":
  34. continue
  35. new_object.set(i, node_data[i])
  1. // Note: This can be called from anywhere inside the tree. This function is
  2. // path independent.
  3. public void LoadGame()
  4. {
  5. if (!FileAccess.FileExists("user://savegame.save"))
  6. {
  7. return; // Error! We don't have a save to load.
  8. }
  9. // We need to revert the game state so we're not cloning objects during loading.
  10. // This will vary wildly depending on the needs of a project, so take care with
  11. // this step.
  12. // For our example, we will accomplish this by deleting saveable objects.
  13. var saveNodes = GetTree().GetNodesInGroup("Persist");
  14. foreach (Node saveNode in saveNodes)
  15. {
  16. saveNode.QueueFree();
  17. }
  18. // Load the file line by line and process that dictionary to restore the object
  19. // it represents.
  20. using var saveGame = FileAccess.Open("user://savegame.save", FileAccess.ModeFlags.Read);
  21. while (saveGame.GetPosition() < saveGame.GetLength())
  22. {
  23. var jsonString = saveGame.GetLine();
  24. // Creates the helper class to interact with JSON
  25. var json = new Json();
  26. var parseResult = json.Parse(jsonString);
  27. if (parseResult != Error.Ok)
  28. {
  29. GD.Print($"JSON Parse Error: {json.GetErrorMessage()} in {jsonString} at line {json.GetErrorLine()}");
  30. continue;
  31. }
  32. // Get the data from the JSON object
  33. var nodeData = new Godot.Collections.Dictionary<string, Variant>((Godot.Collections.Dictionary)json.Data);
  34. // Firstly, we need to create the object and add it to the tree and set its position.
  35. var newObjectScene = GD.Load<PackedScene>(nodeData["Filename"].ToString());
  36. var newObject = newObjectScene.Instantiate<Node>();
  37. GetNode(nodeData["Parent"].ToString()).AddChild(newObject);
  38. newObject.Set(Node2D.PropertyName.Position, new Vector2((float)nodeData["PosX"], (float)nodeData["PosY"]));
  39. // Now we set the remaining variables.
  40. foreach (var (key, value) in nodeData)
  41. {
  42. if (key == "Filename" || key == "Parent" || key == "PosX" || key == "PosY")
  43. {
  44. continue;
  45. }
  46. newObject.Set(key, value);
  47. }
  48. }
  49. }

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.

Some notes

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.

Additionally, our 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 NodePath will likely be invalid.

JSON vs binary serialization

For simple game state, JSON may work and it generates human-readable files that are easy to debug.

But JSON has many limitations. If you need to store more complex game state or a lot of it, binary serialization may be a better approach.

JSON limitations

Here are some important gotchas to know about when using JSON.

  • Filesize: JSON stores data in text format, which is much larger than binary formats.

  • Data types: JSON only offers a limited set of data types. If you have data types that JSON doesn’t have, you will need to translate your data to and from types that JSON can handle. For example, some important types that JSON can’t parse are: Vector2, Vector3, Color, Rect2, and Quaternion.

  • Custom logic needed for encoding/decoding: If you have any custom classes that you want to store with JSON, you will need to write your own logic for encoding and decoding those classes.

Binary serialization

Binary serialization is an alternative approach for storing game state, and you can use it with the functions get_var and store_var of FileAccess.

  • Binary serialization should produce smaller files than JSON.

  • Binary serialization can handle most common data types.

  • Binary serialization requires less custom logic for encoding and decoding custom classes.

Note that not all properties are included. Only properties that are configured with the PROPERTY_USAGE_STORAGE flag set will be serialized. You can add a new usage flag to a property by overriding the _get_property_list method in your class. You can also check how property usage is configured by calling Object._get_property_list. See PropertyUsageFlags for the possible usage flags.