singletons_autoload.rst 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. .. _doc_singletons_autoload:
  2. Singletons (AutoLoad)
  3. =====================
  4. Introduction
  5. ------------
  6. Godot's scene system, while powerful and flexible, has a drawback: there is no
  7. method for storing information (e.g. a player's score or inventory) that is
  8. needed by more than one scene.
  9. It's possible to address this with some workarounds, but they come with their
  10. own limitations:
  11. - You can use a "master" scene that loads and unloads other scenes as
  12. its children. However, this means you can no longer run those scenes
  13. individually and expect them to work correctly.
  14. - Information can be stored to disk in ``user://`` and then loaded by scenes
  15. that require it, but frequently saving and loading data is cumbersome and
  16. may be slow.
  17. The `Singleton pattern <https://en.wikipedia.org/wiki/Singleton_pattern>`_ is
  18. a useful tool for solving the common use case where you need to store
  19. persistent information between scenes. In our case, it's possible to reuse the
  20. same scene or class for multiple singletons as long as they have different
  21. names.
  22. Using this concept, you can create objects that:
  23. - Are always loaded, no matter which scene is currently running.
  24. - Can store global variables such as player information.
  25. - Can handle switching scenes and between-scene transitions.
  26. - *Act* like a singleton, since GDScript does not support global variables by design.
  27. Autoloading nodes and scripts can give us these characteristics.
  28. .. note::
  29. Godot won't make an AutoLoad a "true" singleton as per the singleton design
  30. pattern. It may still be instanced more than once by the user if desired.
  31. AutoLoad
  32. --------
  33. You can create an AutoLoad to load a scene or a script that inherits from
  34. :ref:`class_Node`.
  35. .. note::
  36. When autoloading a script, a :ref:`class_Node` will be created and the script will be
  37. attached to it. This node will be added to the root viewport before any
  38. other scenes are loaded.
  39. .. image:: img/singleton.png
  40. To autoload a scene or script, select **Project > Project Settings** from the
  41. menu and switch to the **AutoLoad** tab.
  42. .. image:: img/autoload_tab.png
  43. Here you can add any number of scenes or scripts. Each entry in the list
  44. requires a name, which is assigned as the node's ``name`` property. The order of
  45. the entries as they are added to the global scene tree can be manipulated using
  46. the up/down arrow keys. Like regular scenes, the engine will read these nodes
  47. in top-to-bottom order.
  48. .. image:: img/autoload_example.png
  49. This means that any node can access a singleton named "PlayerVariables" with:
  50. .. tabs::
  51. .. code-tab:: gdscript GDScript
  52. var player_vars = get_node("/root/PlayerVariables")
  53. player_vars.health -= 10
  54. .. code-tab:: csharp
  55. var playerVariables = GetNode<PlayerVariables>("/root/PlayerVariables");
  56. playerVariables.Health -= 10; // Instance field.
  57. If the **Enable** column is checked (which is the default), then the singleton can
  58. be accessed directly without requiring ``get_node()``:
  59. .. tabs::
  60. .. code-tab:: gdscript GDScript
  61. PlayerVariables.health -= 10
  62. .. code-tab:: csharp
  63. // Static members can be accessed by using the class name.
  64. PlayerVariables.Health -= 10;
  65. Note that autoload objects (scripts and/or scenes) are accessed just like any
  66. other node in the scene tree. In fact, if you look at the running scene tree,
  67. you'll see the autoloaded nodes appear:
  68. .. image:: img/autoload_runtime.png
  69. .. warning::
  70. Autoloads must **not** be removed using ``free()`` or ``queue_free()`` at
  71. runtime, or the engine will crash.
  72. Custom scene switcher
  73. ---------------------
  74. This tutorial will demonstrate building a scene switcher using autoloads.
  75. For basic scene switching, you can use the
  76. :ref:`SceneTree.change_scene() <class_SceneTree_method_change_scene>`
  77. method (see :ref:`doc_scene_tree` for details). However, if you need more
  78. complex behavior when changing scenes, this method provides more functionality.
  79. To begin, download the template from here:
  80. :download:`autoload.zip <files/autoload.zip>` and open it in Godot.
  81. The project contains two scenes: ``Scene1.tscn`` and ``Scene2.tscn``. Each
  82. scene contains a label displaying the scene name and a button with its
  83. ``pressed()`` signal connected. When you run the project, it starts in
  84. ``Scene1.tscn``. However, pressing the button does nothing.
  85. Global.gd
  86. ~~~~~~~~~
  87. Switch to the **Script** tab and create a new script called ``Global.gd``.
  88. Make sure it inherits from ``Node``:
  89. .. image:: img/autoload_script.png
  90. The next step is to add this script to the autoLoad list. Open
  91. **Project > Project Settings** from the menu, switch to the **AutoLoad** tab and
  92. select the script by clicking the browse button or typing its path:
  93. ``res://Global.gd``. Press **Add** to add it to the autoload list:
  94. .. image:: img/autoload_tutorial1.png
  95. Now whenever we run any scene in the project, this script will always be loaded.
  96. Returning to the script, it needs to fetch the current scene in the
  97. `_ready()` function. Both the current scene (the one with the button) and
  98. ``Global.gd`` are children of root, but autoloaded nodes are always first. This
  99. means that the last child of root is always the loaded scene.
  100. .. tabs::
  101. .. code-tab:: gdscript GDScript
  102. extends Node
  103. var current_scene = null
  104. func _ready():
  105. var root = get_tree().root
  106. current_scene = root.get_child(root.get_child_count() - 1)
  107. .. code-tab:: csharp
  108. using Godot;
  109. using System;
  110. public class Global : Godot.Node
  111. {
  112. public Node CurrentScene { get; set; }
  113. public override void _Ready()
  114. {
  115. Viewport root = GetTree().Root;
  116. CurrentScene = root.GetChild(root.GetChildCount() - 1);
  117. }
  118. }
  119. Now we need a function for changing the scene. This function needs to free the
  120. current scene and replace it with the requested one.
  121. .. tabs::
  122. .. code-tab:: gdscript GDScript
  123. func goto_scene(path):
  124. # This function will usually be called from a signal callback,
  125. # or some other function in the current scene.
  126. # Deleting the current scene at this point is
  127. # a bad idea, because it may still be executing code.
  128. # This will result in a crash or unexpected behavior.
  129. # The solution is to defer the load to a later time, when
  130. # we can be sure that no code from the current scene is running:
  131. call_deferred("_deferred_goto_scene", path)
  132. func _deferred_goto_scene(path):
  133. # It is now safe to remove the current scene
  134. current_scene.free()
  135. # Load the new scene.
  136. var s = ResourceLoader.load(path)
  137. # Instance the new scene.
  138. current_scene = s.instance()
  139. # Add it to the active scene, as child of root.
  140. get_tree().root.add_child(current_scene)
  141. # Optionally, to make it compatible with the SceneTree.change_scene() API.
  142. get_tree().current_scene = current_scene
  143. .. code-tab:: csharp
  144. public void GotoScene(string path)
  145. {
  146. // This function will usually be called from a signal callback,
  147. // or some other function from the current scene.
  148. // Deleting the current scene at this point is
  149. // a bad idea, because it may still be executing code.
  150. // This will result in a crash or unexpected behavior.
  151. // The solution is to defer the load to a later time, when
  152. // we can be sure that no code from the current scene is running:
  153. CallDeferred(nameof(DeferredGotoScene), path);
  154. }
  155. public void DeferredGotoScene(string path)
  156. {
  157. // It is now safe to remove the current scene
  158. CurrentScene.Free();
  159. // Load a new scene.
  160. var nextScene = (PackedScene)GD.Load(path);
  161. // Instance the new scene.
  162. CurrentScene = nextScene.Instance();
  163. // Add it to the active scene, as child of root.
  164. GetTree().Root.AddChild(CurrentScene);
  165. // Optionally, to make it compatible with the SceneTree.change_scene() API.
  166. GetTree().CurrentScene = CurrentScene;
  167. }
  168. Using :ref:`Object.call_deferred() <class_Object_method_call_deferred>`,
  169. the second function will only run once all code from the current scene has
  170. completed. Thus, the current scene will not be removed while it is
  171. still being used (i.e. its code is still running).
  172. Finally, we need to fill the empty callback functions in the two scenes:
  173. .. tabs::
  174. .. code-tab:: gdscript GDScript
  175. # Add to 'Scene1.gd'.
  176. func _on_Button_pressed():
  177. Global.goto_scene("res://Scene2.tscn")
  178. .. code-tab:: csharp
  179. // Add to 'Scene1.cs'.
  180. public void OnButtonPressed()
  181. {
  182. var global = GetNode<Global>("/root/Global");
  183. global.GotoScene("res://Scene2.tscn");
  184. }
  185. and
  186. .. tabs::
  187. .. code-tab:: gdscript GDScript
  188. # Add to 'Scene2.gd'.
  189. func _on_Button_pressed():
  190. Global.goto_scene("res://Scene1.tscn")
  191. .. code-tab:: csharp
  192. // Add to 'Scene2.cs'.
  193. public void OnButtonPressed()
  194. {
  195. var global = GetNode<Global>("/root/Global");
  196. global.GotoScene("res://Scene1.tscn");
  197. }
  198. Run the project and test that you can switch between scenes by pressing
  199. the button.
  200. .. note::
  201. When scenes are small, the transition is instantaneous. However, if your
  202. scenes are more complex, they may take a noticeable amount of time to appear.
  203. To learn how to handle this, see the next tutorial: :ref:`doc_background_loading`.
  204. Alternatively, if the loading time is relatively short (less than 3 seconds or so),
  205. you can display a "loading plaque" by showing some kind of 2D element just before
  206. changing the scene. You can then hide it just after the scene is changed. This can
  207. be used to indicate to the player that a scene is being loaded.