scene_organization.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. .. _doc_scene_organization:
  2. Scene organization
  3. ==================
  4. This article covers topics related to the effective organization of
  5. scene content. Which nodes should one use? Where should one place them?
  6. How should they interact?
  7. How to build relationships effectively
  8. --------------------------------------
  9. When Godot users begin crafting their own scenes, they often run into the
  10. following problem:
  11. They create their first scene and fill it with content only to eventually end
  12. up saving branches of their scene into separate scenes as the nagging feeling
  13. that they should split things up starts to accumulate. However, they then
  14. notice that the hard references they were able to rely on before are no longer
  15. possible. Re-using the scene in multiple places creates issues because the
  16. node paths do not find their targets and signal connections established in the
  17. editor break.
  18. To fix these problems, one must instantiate the sub-scenes without them
  19. requiring details about their environment. One needs to be able to trust
  20. that the sub-scene will create itself without being picky about how one uses
  21. it.
  22. One of the biggest things to consider in OOP is maintaining
  23. focused, singular-purpose classes with
  24. `loose coupling <https://en.wikipedia.org/wiki/Loose_coupling>`_
  25. to other parts of the codebase. This keeps the size of objects small (for
  26. maintainability) and improves their reusability.
  27. These OOP best practices have *several* implications for best practices
  28. in scene structure and script usage.
  29. **If at all possible, one should design scenes to have no dependencies.**
  30. That is, one should create scenes that keep everything they need within
  31. themselves.
  32. If a scene must interact with an external context, experienced developers
  33. recommend the use of
  34. `Dependency Injection <https://en.wikipedia.org/wiki/Dependency_injection>`_.
  35. This technique involves having a high-level API provide the dependencies of the
  36. low-level API. Why do this? Because classes which rely on their external
  37. environment can inadvertently trigger bugs and unexpected behavior.
  38. To do this, one must expose data and then rely on a parent context to
  39. initialize it:
  40. 1. Connect to a signal. Extremely safe, but should be used only to "respond" to
  41. behavior, not start it. By convention, signal names are usually past-tense verbs
  42. like "entered", "skill_activated", or "item_collected".
  43. .. tabs::
  44. .. code-tab:: gdscript GDScript
  45. # Parent
  46. $Child.signal_name.connect(method_on_the_object)
  47. # Child
  48. signal_name.emit() # Triggers parent-defined behavior.
  49. .. code-tab:: csharp
  50. // Parent
  51. GetNode("Child").Connect("SignalName", ObjectWithMethod, "MethodOnTheObject");
  52. // Child
  53. EmitSignal("SignalName"); // Triggers parent-defined behavior.
  54. 2. Call a method. Used to start behavior.
  55. .. tabs::
  56. .. code-tab:: gdscript GDScript
  57. # Parent
  58. $Child.method_name = "do"
  59. # Child, assuming it has String property 'method_name' and method 'do'.
  60. call(method_name) # Call parent-defined method (which child must own).
  61. .. code-tab:: csharp
  62. // Parent
  63. GetNode("Child").Set("MethodName", "Do");
  64. // Child
  65. Call(MethodName); // Call parent-defined method (which child must own).
  66. 3. Initialize a :ref:`Callable <class_Callable>` property. Safer than a method
  67. as ownership of the method is unnecessary. Used to start behavior.
  68. .. tabs::
  69. .. code-tab:: gdscript GDScript
  70. # Parent
  71. $Child.func_property = object_with_method.method_on_the_object
  72. # Child
  73. func_property.call() # Call parent-defined method (can come from anywhere).
  74. .. code-tab:: csharp
  75. // Parent
  76. GetNode("Child").Set("FuncProperty", Callable.From(ObjectWithMethod.MethodOnTheObject));
  77. // Child
  78. FuncProperty.Call(); // Call parent-defined method (can come from anywhere).
  79. 4. Initialize a Node or other Object reference.
  80. .. tabs::
  81. .. code-tab:: gdscript GDScript
  82. # Parent
  83. $Child.target = self
  84. # Child
  85. print(target) # Use parent-defined node.
  86. .. code-tab:: csharp
  87. // Parent
  88. GetNode("Child").Set("Target", this);
  89. // Child
  90. GD.Print(Target); // Use parent-defined node.
  91. 5. Initialize a NodePath.
  92. .. tabs::
  93. .. code-tab:: gdscript GDScript
  94. # Parent
  95. $Child.target_path = ".."
  96. # Child
  97. get_node(target_path) # Use parent-defined NodePath.
  98. .. code-tab:: csharp
  99. // Parent
  100. GetNode("Child").Set("TargetPath", NodePath(".."));
  101. // Child
  102. GetNode(TargetPath); // Use parent-defined NodePath.
  103. These options hide the points of access from the child node. This in turn
  104. keeps the child **loosely coupled** to its environment. One can reuse it
  105. in another context without any extra changes to its API.
  106. .. note::
  107. Although the examples above illustrate parent-child relationships,
  108. the same principles apply towards all object relations. Nodes which
  109. are siblings should only be aware of their hierarchies while an ancestor
  110. mediates their communications and references.
  111. .. tabs::
  112. .. code-tab:: gdscript GDScript
  113. # Parent
  114. $Left.target = $Right.get_node("Receiver")
  115. # Left
  116. var target: Node
  117. func execute():
  118. # Do something with 'target'.
  119. # Right
  120. func _init():
  121. var receiver = Receiver.new()
  122. add_child(receiver)
  123. .. code-tab:: csharp
  124. // Parent
  125. GetNode<Left>("Left").Target = GetNode("Right/Receiver");
  126. public partial class Left : Node
  127. {
  128. public Node Target = null;
  129. public void Execute()
  130. {
  131. // Do something with 'Target'.
  132. }
  133. }
  134. public partial class Right : Node
  135. {
  136. public Node Receiver = null;
  137. public Right()
  138. {
  139. Receiver = ResourceLoader.Load<Script>("Receiver.cs").New();
  140. AddChild(Receiver);
  141. }
  142. }
  143. The same principles also apply to non-Node objects that maintain dependencies
  144. on other objects. Whichever object actually owns the objects should manage
  145. the relationships between them.
  146. .. warning::
  147. One should favor keeping data in-house (internal to a scene) though as
  148. placing a dependency on an external context, even a loosely coupled one,
  149. still means that the node will expect something in its environment to be
  150. true. The project's design philosophies should prevent this from happening.
  151. If not, the code's inherent liabilities will force developers to use
  152. documentation to keep track of object relations on a microscopic scale; this
  153. is otherwise known as development hell. Writing code that relies on external
  154. documentation for one to use it safely is error-prone by default.
  155. To avoid creating and maintaining such documentation, one converts the
  156. dependent node ("child" above) into a tool script that implements
  157. ``_get_configuration_warnings()``.
  158. Returning a non-empty PackedStringArray from it will make the Scene dock generate a
  159. warning icon with the string(s) as a tooltip by the node. This is the same icon
  160. that appears for nodes such as the
  161. :ref:`Area2D <class_Area2D>` node when it has no child
  162. :ref:`CollisionShape2D <class_CollisionShape2D>` nodes defined. The editor
  163. then self-documents the scene through the script code. No content duplication
  164. via documentation is necessary.
  165. A GUI like this can better inform project users of critical information about
  166. a Node. Does it have external dependencies? Have those dependencies been
  167. satisfied? Other programmers, and especially designers and writers, will need
  168. clear instructions in the messages telling them what to do to configure it.
  169. So, why does all this complex switcharoo work? Well, because scenes operate
  170. best when they operate alone. If unable to work alone, then working with
  171. others anonymously (with minimal hard dependencies, i.e. loose coupling)
  172. is the next best thing. Inevitably, changes may need to be made to a class and
  173. if these changes cause it to interact with other scenes in unforeseen ways,
  174. then things will start to break down. The whole point of all this indirection
  175. is to avoid ending up in a situation where changing one class results in
  176. adversely effecting other classes dependent on it.
  177. Scripts and scenes, as extensions of engine classes, should abide
  178. by *all* OOP principles. Examples include...
  179. - `SOLID <https://en.wikipedia.org/wiki/SOLID>`_
  180. - `DRY <https://en.wikipedia.org/wiki/Don%27t_repeat_yourself>`_
  181. - `KISS <https://en.wikipedia.org/wiki/KISS_principle>`_
  182. - `YAGNI <https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it>`_
  183. Choosing a node tree structure
  184. ------------------------------
  185. So, a developer starts work on a game only to stop at the vast possibilities
  186. before them. They might know what they want to do, what systems they want to
  187. have, but *where* to put them all? Well, how one goes about making their game
  188. is always up to them. One can construct node trees in countless ways.
  189. But, for those who are unsure, this helpful guide can give them a sample of
  190. a decent structure to start with.
  191. A game should always have a sort of "entry point"; somewhere the developer can
  192. definitively track where things begin so that they can follow the logic as it
  193. continues elsewhere. This place also serves as a bird's eye view of all of the
  194. other data and logic in the program. For traditional applications, this would
  195. be the "main" function. In this case, it would be a Main node.
  196. - Node "Main" (main.gd)
  197. The ``main.gd`` script would then serve as the primary controller of one's
  198. game.
  199. Then one has their actual in-game "World" (a 2D or 3D one). This can be a child
  200. of Main. In addition, one will need a primary GUI for their game that manages
  201. the various menus and widgets the project needs.
  202. - Node "Main" (main.gd)
  203. - Node2D/Node3D "World" (game_world.gd)
  204. - Control "GUI" (gui.gd)
  205. When changing levels, one can then swap out the children of the "World" node.
  206. :ref:`Changing scenes manually <doc_change_scenes_manually>` gives users full
  207. control over how their game world transitions.
  208. The next step is to consider what gameplay systems one's project requires.
  209. If one has a system that...
  210. 1. tracks all of its data internally
  211. 2. should be globally accessible
  212. 3. should exist in isolation
  213. ... then one should create an :ref:`autoload 'singleton' node <doc_singletons_autoload>`.
  214. .. note::
  215. For smaller games, a simpler alternative with less control would be to have
  216. a "Game" singleton that simply calls the
  217. :ref:`SceneTree.change_scene_to_file() <class_SceneTree_method_change_scene_to_file>` method
  218. to swap out the main scene's content. This structure more or less keeps
  219. the "World" as the main game node.
  220. Any GUI would need to also be a
  221. singleton; be a transitory part of the "World"; or be manually added as a
  222. direct child of the root. Otherwise, the GUI nodes would also delete
  223. themselves during scene transitions.
  224. If one has systems that modify other systems' data, one should define those as
  225. their own scripts or scenes rather than autoloads. For more information on the
  226. reasons, please see the
  227. :ref:`Autoloads versus regular nodes <doc_autoloads_versus_internal_nodes>`
  228. documentation.
  229. Each subsystem within one's game should have its own section within the
  230. SceneTree. One should use parent-child relationships only in cases where nodes
  231. are effectively elements of their parents. Does removing the parent reasonably
  232. mean that one should also remove the children? If not, then it should have its
  233. own place in the hierarchy as a sibling or some other relation.
  234. .. note::
  235. In some cases, one needs these separated nodes to *also* position themselves
  236. relative to each other. One can use the
  237. :ref:`RemoteTransform <class_RemoteTransform3D>` /
  238. :ref:`RemoteTransform2D <class_RemoteTransform2D>` nodes for this purpose.
  239. They will allow a target node to conditionally inherit selected transform
  240. elements from the Remote\* node. To assign the ``target``
  241. :ref:`NodePath <class_NodePath>`, use one of the following:
  242. 1. A reliable third party, likely a parent node, to mediate the assignment.
  243. 2. A group, to easily pull a reference to the desired node (assuming there
  244. will only ever be one of the targets).
  245. When should one do this? Well, this is subjective. The dilemma arises when
  246. one must micro-manage when a node must move around the SceneTree to preserve
  247. itself. For example...
  248. - Add a "player" node to a "room".
  249. - Need to change rooms, so one must delete the current room.
  250. - Before the room can be deleted, one must preserve and/or move the player.
  251. Is memory a concern?
  252. - If not, one can just create the two rooms, move the player
  253. and delete the old one. No problem.
  254. If so, one will need to...
  255. - Move the player somewhere else in the tree.
  256. - Delete the room.
  257. - Instantiate and add the new room.
  258. - Re-add the player.
  259. The issue is that the player here is a "special case"; one where the
  260. developers must *know* that they need to handle the player this way for the
  261. project. As such, the only way to reliably share this information as a team
  262. is to *document* it. Keeping implementation details in documentation however
  263. is dangerous. It's a maintenance burden, strains code readability, and bloats
  264. the intellectual content of a project unnecessarily.
  265. In a more complex game with larger assets, it can be a better idea to simply
  266. keep the player somewhere else in the SceneTree entirely. This results in:
  267. 1. More consistency.
  268. 2. No "special cases" that must be documented and maintained somewhere.
  269. 3. No opportunity for errors to occur because these details are not accounted
  270. for.
  271. In contrast, if one ever needs to have a child node that does *not* inherit
  272. the transform of their parent, one has the following options:
  273. 1. The **declarative** solution: place a :ref:`Node <class_Node>` in between
  274. them. As nodes with no transform, Nodes will not pass along such
  275. information to their children.
  276. 2. The **imperative** solution: Use the ``top_level`` property for the
  277. :ref:`CanvasItem <class_CanvasItem_property_top_level>` or
  278. :ref:`Node3D <class_Node3D_property_top_level>` node. This will make
  279. the node ignore its inherited transform.
  280. .. note::
  281. If building a networked game, keep in mind which nodes and gameplay systems
  282. are relevant to all players versus those just pertinent to the authoritative
  283. server. For example, users do not all need to have a copy of every players'
  284. "PlayerController" logic. Instead, they need only their own. As such, keeping
  285. these in a separate branch from the "world" can help simplify the management
  286. of game connections and the like.
  287. The key to scene organization is to consider the SceneTree in relational terms
  288. rather than spatial terms. Are the nodes dependent on their parent's existence?
  289. If not, then they can thrive all by themselves somewhere else.
  290. If they are dependent, then it stands to reason that they should be children of
  291. that parent (and likely part of that parent's scene if they aren't already).
  292. Does this mean nodes themselves are components? Not at all.
  293. Godot's node trees form an aggregation relationship, not one of composition.
  294. But while one still has the flexibility to move nodes around, it is still best
  295. when such moves are unnecessary by default.