Up to date
This page is up to date for Godot
If you still find outdated information, please open an issue.
Autoloads versus regular nodes¶
Godot offers a feature to automatically load nodes at the root of your project, allowing you to access them globally, that can fulfill the role of a Singleton: Singletons (Autoload). These autoloaded nodes are not freed when you change the scene from code with SceneTree.change_scene_to_file.
In this guide, you will learn when to use the Autoload feature, and techniques you can use to avoid it.
The cutting audio issue¶
Other engines can encourage the use of creating manager classes, singletons that organize a lot of functionality into a globally accessible object. Godot offers many ways to avoid global state thanks to the node tree and signals.
For example, let's say we are building a platformer and want to collect coins
that play a sound effect. There's a node for that: the AudioStreamPlayer. But if we call the
AudioStreamPlayer while it is
already playing a sound, the new sound interrupts the first.
A solution is to code a global, autoloaded sound manager class. It generates a
AudioStreamPlayer nodes that cycle through as each new request for
sound effects comes in. Say we call that class
Sound, you can use it from
anywhere in your project by calling
solves the problem in the short term but causes more problems:
Global state: one object is now responsible for all objects' data. If the
Soundclass has errors or doesn't have an AudioStreamPlayer available, all the nodes calling it can break.
Global access: now that any object can call
Sound.play(sound_path)from anywhere, there's no longer an easy way to find the source of a bug.
Global resource allocation: with a pool of
AudioStreamPlayernodes stored from the start, you can either have too few and face bugs, or too many and use more memory than you need.
About global access, the problem is that any code anywhere could pass wrong
data to the
Sound autoload in our example. As a result, the domain to
explore to fix the bug spans the entire project.
When you keep code inside a scene, only one or two scripts may be involved in audio.
Contrast this with each scene keeping as many
AudioStreamPlayer nodes as it
needs within itself and all these problems go away:
Each scene manages its own state information. If there is a problem with the data, it will only cause issues in that one scene.
Each scene accesses only its own nodes. Now, if there is a bug, it's easy to find which node is at fault.
Each scene allocates exactly the amount of resources it needs.