See all glossary terms

Serialization

In programming, "serializing" is the process of taking objects or data in the computer's memory and encoding them in a format that can be saved to a hard drive or shared over a network. The encoding process is called "serialization", and the resulting data can be human-readable if it is in a text format, or it can be binary data that only computers can understand.
In other words, we use serialized files to save data. Game savefiles are serialized data, multiplayer network information is also serialized data, and Godot scenes or resources are another form of serialized data.
For example, when a player saves their game, we might want to capture key pieces of information about the running game's current state:
  • The player's position.
  • The player's health.
  • The enemies that are still present in the level and their positions.
  • The items the player has collected.
  • The time elapsed since the game started.
And more.
To save the player's progress, we collect all that information from the computer's memory and serialize it; we convert it to a format that can be saved to disk. When the player loads their game, we load the save file, read its contents, and then deserialize it: we restore the game's state from the data in the file.
In Godot, you generally don't need to write special code to serialize or format data to save it because everything in Godot is already serializable. The feature is built into the engine, and you can save and load scenes and resources with a single line of code.
Here's an example of a script defining a new resource type with two exported variables that you want to save:
class_name GameData extends Resource

const SAVE_PATH := "user://game_data.tres"

@export var player_position := Vector2.ZERO
@export var player_health := 10

func save() -> void:
    ResourceSaver.save(self, SAVE_PATH)
If you call the resource's save() method above, Godot will automatically save any property annotated with @export. Depending on the file extension you use, it can save it as text or binary data. In the example above, we save the file using the .tres extension, which stands for "text resource". So, the file will be text-based and human-readable. If you want to save it as binary data, you can use the .res extension instead.
You can use the GDScript language's load() function to load the data. The following code will load the data from the file if it exists or create a new GameData object if it doesn't:
func load() -> GameData:
    var game_data := load(GameData.SAVE_PATH)
    if game_data == null:
        return GameData.new()
    else:
        return game_data
Did you know?
All scenes and resources in the editor are serialized Godot game data, and you can save your running game as scenes exactly the same way.
The Godot editor is just a Godot game, after all!

See Also

Related terms in the Glossary