Up to date
This page is up to date for Godot 4.2
.
If you still find outdated information, please open an issue.
Chargements automatiques contre nœuds normaux¶
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.
Dans ce guide, vous apprendrez quand utiliser la fonction de Chargement Automatique et les techniques que vous pouvez utiliser pour l'éviter.
Le problème du son qui coupe¶
D'autres moteurs pourraient encourager l'utilisation de la création de classes "manager" qui organisent un grand nombre de fonctionnalités en une entité globalement accessible. Godot fournit de nombreux moyens d'éviter d'utiliser un état global grâce à l'arbre des nœuds et aux signaux.
Par exemple, que se passe-t-il si un développeur construit un platformer et qu'il veut collectionner des pièces qui jouent un effet sonore ? Eh bien, il y a un nœud pour cela : le AudioStreamPlayer. Mais si on appelle un AudioStreamPlayer
alors qu'il joue déjà un son, alors le nouveau son interrompt le précédent.
A solution is to code a global, autoloaded sound manager class. It generates a
pool of 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 Sound.play("coin_pickup.ogg")
. This
solves the problem in the short term but causes more problems:
État global : un seul objet est maintenant responsable des données de tous les objets. Si la classe
Sound
a des erreurs ou n'a pas d'AudioStreamPlayer disponible, tous les nœuds qui l'appellent vont dysfonctionner.Accès global : maintenant que n'importe quel objet peut appeler ``Sound.play(sound_path)``de n'importe où, il n'y a plus de moyen facile de trouver la source d'un bug.
Allocation globale des ressources : avec un pool de nœuds
AudioStreamPlayer
stockés dès le départ, vous pouvez en avoir trop peu et rencontrer des bugs, ou en avoir trop et utiliser plus de mémoire que nécessaire.
Note
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.
Lorsque vous gardez le code à l'intérieur d'une scène, un ou deux scripts seulement peuvent être impliqués dans l'audio.
Comparez cela avec chaque scène qui garde autant de nœuds AudioStreamPlayer
qu'il lui faut et tous ces problèmes disparaissent :
Chaque scène gère ses propres informations d'état. S'il y a un problème avec les données, cela ne causera des problèmes que dans une seule scène.
Chaque scène accède uniquement à ses propres nœuds. Ainsi, si il y a un bug, il est facile de trouver quel nœud pose problème.
Chaque scène alloue exactement la quantité de ressources dont elle a besoin.
Quand utiliser un Chargement Automatique¶
GDScript supports the creation of static
functions using static func
.
When combined with class_name
, this makes it possible to create libraries of
helper functions without having to create an instance to call them. The
limitation of static functions is that they can't reference member variables,
non-static functions or self
.
Since Godot 4.1, GDScript also supports static
variables using static var
.
This means you can now share a variables across instances of a class without
having to create a separate autoload.
Still, autoloaded nodes can simplify your code for systems with a wide scope. If the autoload is managing its own information and not invading the data of other objects, then it's a great way to create systems that handle broad-scoped tasks. For example, a quest or a dialogue system.
Note
An autoload is not necessarily a singleton. Nothing prevents you from instantiating copies of an autoloaded node. An autoload is only a tool that makes a node load automatically as a child of the root of your scene tree, regardless of your game's node structure or which scene you run, e.g. by pressing the F6 key.
As a result, you can get the autoloaded node, for example an autoload called
Sound
, by calling get_node("/root/Sound")
.