Singletons (Autoload)

Introduction

Godot’s scene system, while powerful and flexible, has a drawback: there is no method for storing information (e.g. a player’s score or inventory) that is needed by more than one scene.

It’s possible to address this with some workarounds, but they come with their own limitations:

  • You can use a “master” scene that loads and unloads other scenes as its children. However, this means you can no longer run those scenes individually and expect them to work correctly.

  • Information can be stored to disk in user:// and then loaded by scenes that require it, but frequently saving and loading data is cumbersome and may be slow.

The Singleton pattern is a useful tool for solving the common use case where you need to store persistent information between scenes. In our case, it’s possible to reuse the same scene or class for multiple singletons as long as they have different names.

Using this concept, you can create objects that:

  • Are always loaded, no matter which scene is currently running.

  • Can store global variables such as player information.

  • Can handle switching scenes and between-scene transitions.

  • Act like a singleton, since GDScript does not support global variables by design.

Autoloading nodes and scripts can give us these characteristics.

Note

Godot won’t make an Autoload a “true” singleton as per the singleton design pattern. It may still be instanced more than once by the user if desired.

Tip

If you’re creating an autoload as part of an editor plugin, consider registering it automatically in the Project Settings when the plugin is enabled.

Autoload

You can create an Autoload to load a scene or a script that inherits from Node.

Note

When autoloading a script, a Node will be created and the script will be attached to it. This node will be added to the root viewport before any other scenes are loaded.

../../_images/singleton.webp

To autoload a scene or script, select Project > Project Settings from the menu and switch to the Autoload tab.

../../_images/autoload_tab.webp

Here you can add any number of scenes or scripts. Each entry in the list requires a name, which is assigned as the node’s name property. The order of the entries as they are added to the global scene tree can be manipulated using the up/down arrow keys. Like regular scenes, the engine will read these nodes in top-to-bottom order.

../../_images/autoload_example.webp

This means that any node can access a singleton named “PlayerVariables” with:

GDScriptC#

  1. var player_vars = get_node("/root/PlayerVariables")
  2. player_vars.health -= 10
  1. var playerVariables = GetNode<PlayerVariables>("/root/PlayerVariables");
  2. playerVariables.Health -= 10; // Instance field.

If the Enable column is checked (which is the default), then the singleton can be accessed directly in GDScript, without requiring get_node():

GDScript

  1. PlayerVariables.health -= 10

Note that autoload objects (scripts and/or scenes) are accessed just like any other node in the scene tree. In fact, if you look at the running scene tree, you’ll see the autoloaded nodes appear:

../../_images/autoload_runtime.webp

Warning

Autoloads must not be removed using free() or queue_free() at runtime, or the engine will crash.

Custom scene switcher

This tutorial will demonstrate building a scene switcher using autoloads. For basic scene switching, you can use the SceneTree.change_scene_to_file() method (see Using SceneTree for details). However, if you need more complex behavior when changing scenes, this method provides more functionality.

To begin, download the template from here: singleton_autoload_starter.zip and open it in Godot.

The project contains two scenes: scene_1.tscn and scene_2.tscn. Each scene contains a label displaying the scene name and a button with its pressed() signal connected. When you run the project, it starts in scene_1.tscn. However, pressing the button does nothing.

Creating the script

Open the Script window and create a new script called global.gd. Make sure it inherits from Node:

../../_images/autoload_script.webp

The next step is to add this script to the autoLoad list. Open Project > Project Settings from the menu, switch to the Autoload tab and select the script by clicking the browse button or typing its path: res://global.gd. Press Add to add it to the autoload list:

../../_images/autoload_tutorial1.webp

Now whenever we run any scene in the project, this script will always be loaded.

Returning to the script, it needs to fetch the current scene in the _ready() function. Both the current scene (the one with the button) and global.gd are children of root, but autoloaded nodes are always first. This means that the last child of root is always the loaded scene.

GDScriptC#

  1. extends Node
  2. var current_scene = null
  3. func _ready():
  4. var root = get_tree().root
  5. current_scene = root.get_child(root.get_child_count() - 1)
  1. using Godot;
  2. public partial class Global : Node
  3. {
  4. public Node CurrentScene { get; set; }
  5. public override void _Ready()
  6. {
  7. Viewport root = GetTree().Root;
  8. CurrentScene = root.GetChild(root.GetChildCount() - 1);
  9. }
  10. }

Now we need a function for changing the scene. This function needs to free the current scene and replace it with the requested one.

GDScriptC#

  1. func goto_scene(path):
  2. # This function will usually be called from a signal callback,
  3. # or some other function in the current scene.
  4. # Deleting the current scene at this point is
  5. # a bad idea, because it may still be executing code.
  6. # This will result in a crash or unexpected behavior.
  7. # The solution is to defer the load to a later time, when
  8. # we can be sure that no code from the current scene is running:
  9. call_deferred("_deferred_goto_scene", path)
  10. func _deferred_goto_scene(path):
  11. # It is now safe to remove the current scene.
  12. current_scene.free()
  13. # Load the new scene.
  14. var s = ResourceLoader.load(path)
  15. # Instance the new scene.
  16. current_scene = s.instantiate()
  17. # Add it to the active scene, as child of root.
  18. get_tree().root.add_child(current_scene)
  19. # Optionally, to make it compatible with the SceneTree.change_scene_to_file() API.
  20. get_tree().current_scene = current_scene
  1. public void GotoScene(string path)
  2. {
  3. // This function will usually be called from a signal callback,
  4. // or some other function from the current scene.
  5. // Deleting the current scene at this point is
  6. // a bad idea, because it may still be executing code.
  7. // This will result in a crash or unexpected behavior.
  8. // The solution is to defer the load to a later time, when
  9. // we can be sure that no code from the current scene is running:
  10. CallDeferred(MethodName.DeferredGotoScene, path);
  11. }
  12. public void DeferredGotoScene(string path)
  13. {
  14. // It is now safe to remove the current scene.
  15. CurrentScene.Free();
  16. // Load a new scene.
  17. var nextScene = GD.Load<PackedScene>(path);
  18. // Instance the new scene.
  19. CurrentScene = nextScene.Instantiate();
  20. // Add it to the active scene, as child of root.
  21. GetTree().Root.AddChild(CurrentScene);
  22. // Optionally, to make it compatible with the SceneTree.change_scene_to_file() API.
  23. GetTree().CurrentScene = CurrentScene;
  24. }

Using Object.call_deferred(), the second function will only run once all code from the current scene has completed. Thus, the current scene will not be removed while it is still being used (i.e. its code is still running).

Finally, we need to fill the empty callback functions in the two scenes:

GDScriptC#

  1. # Add to 'scene_1.gd'.
  2. func _on_button_pressed():
  3. Global.goto_scene("res://scene_2.tscn")
  1. // Add to 'Scene1.cs'.
  2. private void OnButtonPressed()
  3. {
  4. var global = GetNode<Global>("/root/Global");
  5. global.GotoScene("res://Scene2.tscn");
  6. }

and

GDScriptC#

  1. # Add to 'scene_2.gd'.
  2. func _on_button_pressed():
  3. Global.goto_scene("res://scene_1.tscn")
  1. // Add to 'Scene2.cs'.
  2. private void OnButtonPressed()
  3. {
  4. var global = GetNode<Global>("/root/Global");
  5. global.GotoScene("res://Scene1.tscn");
  6. }

Run the project and test that you can switch between scenes by pressing the button.

Note

When scenes are small, the transition is instantaneous. However, if your scenes are more complex, they may take a noticeable amount of time to appear. To learn how to handle this, see the next tutorial: Background loading.

Alternatively, if the loading time is relatively short (less than 3 seconds or so), you can display a “loading plaque” by showing some kind of 2D element just before changing the scene. You can then hide it just after the scene is changed. This can be used to indicate to the player that a scene is being loaded.

Previous Next


© Copyright 2014-present Juan Linietsky, Ariel Manzur and the Godot community (CC BY 3.0). Revision 53e837c6.

Built with Sphinx using a theme provided by Read the Docs.