logic_preferences.rst 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. .. _doc_logic_preferences:
  2. Logic preferences
  3. =================
  4. Ever wondered whether one should approach problem X with strategy Y or Z?
  5. This article covers a variety of topics related to these dilemmas.
  6. Adding nodes and changing properties: which first?
  7. --------------------------------------------------
  8. When initializing nodes from a script at runtime, you may need to change
  9. properties such as the node's name or position. A common dilemma is, when
  10. should you change those values?
  11. It is the best practice to change values on a node before adding it to the
  12. scene tree. Some property's setters have code to update other
  13. corresponding values, and that code can be slow! For most cases, this code
  14. has no impact on your game's performance, but in heavy use cases such as
  15. procedural generation, it can bring your game to a crawl.
  16. For these reasons, it is always a best practice to set the initial values
  17. of a node before adding it to the scene tree.
  18. Loading vs. preloading
  19. ----------------------
  20. In GDScript, there exists the global
  21. :ref:`preload <class_@GDScript_method_preload>` method. It loads resources as
  22. early as possible to front-load the "loading" operations and avoid loading
  23. resources while in the middle of performance-sensitive code.
  24. Its counterpart, the :ref:`load <class_@GDScript_method_load>` method, loads a
  25. resource only when it reaches the load statement. That is, it will load a
  26. resource in-place which can cause slowdowns when it occurs in the middle of
  27. sensitive processes. The ``load()`` function is also an alias for
  28. :ref:`ResourceLoader.load(path) <class_ResourceLoader_method_load>` which is
  29. accessible to *all* scripting languages.
  30. So, when exactly does preloading occur versus loading, and when should one use
  31. either? Let's see an example:
  32. .. tabs::
  33. .. code-tab:: gdscript GDScript
  34. # my_buildings.gd
  35. extends Node
  36. # Note how constant scripts/scenes have a different naming scheme than
  37. # their property variants.
  38. # This value is a constant, so it spawns when the Script object loads.
  39. # The script is preloading the value. The advantage here is that the editor
  40. # can offer autocompletion since it must be a static path.
  41. const BuildingScn = preload("res://building.tscn")
  42. # 1. The script preloads the value, so it will load as a dependency
  43. # of the 'my_buildings.gd' script file. But, because this is a
  44. # property rather than a constant, the object won't copy the preloaded
  45. # PackedScene resource into the property until the script instantiates
  46. # with .new().
  47. #
  48. # 2. The preloaded value is inaccessible from the Script object alone. As
  49. # such, preloading the value here actually does not benefit anyone.
  50. #
  51. # 3. Because the user exports the value, if this script stored on
  52. # a node in a scene file, the scene instantiation code will overwrite the
  53. # preloaded initial value anyway (wasting it). It's usually better to
  54. # provide null, empty, or otherwise invalid default values for exports.
  55. #
  56. # 4. It is when one instantiates this script on its own with .new() that
  57. # one will load "office.tscn" rather than the exported value.
  58. @export var a_building : PackedScene = preload("office.tscn")
  59. # Uh oh! This results in an error!
  60. # One must assign constant values to constants. Because `load` performs a
  61. # runtime lookup by its very nature, one cannot use it to initialize a
  62. # constant.
  63. const OfficeScn = load("res://office.tscn")
  64. # Successfully loads and only when one instantiates the script! Yay!
  65. var office_scn = load("res://office.tscn")
  66. .. code-tab:: csharp
  67. using Godot;
  68. // C# and other languages have no concept of "preloading".
  69. public partial class MyBuildings : Node
  70. {
  71. //This is a read-only field, it can only be assigned when it's declared or during a constructor.
  72. public readonly PackedScene Building = ResourceLoader.Load<PackedScene>("res://building.tscn");
  73. public PackedScene ABuilding;
  74. public override void _Ready()
  75. {
  76. // Can assign the value during initialization.
  77. ABuilding = GD.Load<PackedScene>("res://Office.tscn");
  78. }
  79. }
  80. .. code-tab:: cpp C++
  81. using namespace godot;
  82. class MyBuildings : public Node {
  83. GDCLASS(MyBuildings, Node)
  84. public:
  85. const Ref<PackedScene> building = ResourceLoader::get_singleton()->load("res://building.tscn");
  86. Ref<PackedScene> a_building;
  87. virtual void _ready() override {
  88. // Can assign the value during initialization.
  89. a_building = ResourceLoader::get_singleton()->load("res://office.tscn");
  90. }
  91. };
  92. Preloading allows the script to handle all the loading the moment one loads the
  93. script. Preloading is useful, but there are also times when one doesn't wish
  94. for it. To distinguish these situations, there are a few things one can
  95. consider:
  96. 1. If one cannot determine when the script might load, then preloading a
  97. resource, especially a scene or script, could result in further loads one
  98. does not expect. This could lead to unintentional, variable-length
  99. load times on top of the original script's load operations.
  100. 2. If something else could replace the value (like a scene's exported
  101. initialization), then preloading the value has no meaning. This point isn't
  102. a significant factor if one intends to always create the script on its own.
  103. 3. If one wishes only to 'import' another class resource (script or scene),
  104. then using a preloaded constant is often the best course of action. However,
  105. in exceptional cases, one may wish not to do this:
  106. 1. If the 'imported' class is liable to change, then it should be a property
  107. instead, initialized either using an ``@export`` or a ``load()`` (and
  108. perhaps not even initialized until later).
  109. 2. If the script requires a great many dependencies, and one does not wish
  110. to consume so much memory, then one may wish to, load and unload various
  111. dependencies at runtime as circumstances change. If one preloads
  112. resources into constants, then the only way to unload these resources
  113. would be to unload the entire script. If they are instead loaded
  114. properties, then one can set them to ``null`` and remove all references
  115. to the resource entirely (which, as a
  116. :ref:`RefCounted <class_RefCounted>`-extending type, will cause the
  117. resources to delete themselves from memory).
  118. Large levels: static vs. dynamic
  119. --------------------------------
  120. If one is creating a large level, which circumstances are most appropriate?
  121. Should they create the level as one static space? Or should they load the
  122. level in pieces and shift the world's content as needed?
  123. Well, the simple answer is, "when the performance requires it." The
  124. dilemma associated with the two options is one of the age-old programming
  125. choices: does one optimize memory over speed, or vice versa?
  126. The naive answer is to use a static level that loads everything at once.
  127. But, depending on the project, this could consume a large amount of
  128. memory. Wasting users' RAM leads to programs running slow or outright
  129. crashing from everything else the computer tries to do at the same time.
  130. No matter what, one should break larger scenes into smaller ones (to aid
  131. in reusability of assets). Developers can then design a node that manages the
  132. creation/loading and deletion/unloading of resources and nodes in real-time.
  133. Games with large and varied environments or procedurally generated
  134. elements often implement these strategies to avoid wasting memory.
  135. On the flip side, coding a dynamic system is more complex, i.e. uses more
  136. programmed logic, which results in opportunities for errors and bugs. If one
  137. isn't careful, they can develop a system that bloats the technical debt of
  138. the application.
  139. As such, the best options would be...
  140. 1. To use a static level for smaller games.
  141. 2. If one has the time/resources on a medium/large game, create a library or
  142. plugin that can code the management of nodes and resources. If refined
  143. over time, so as to improve usability and stability, then it could evolve
  144. into a reliable tool across projects.
  145. 3. Code the dynamic logic for a medium/large game because one has the coding
  146. skills, but not the time or resources to refine the code (game's
  147. gotta get done). Could potentially refactor later to outsource the code
  148. into a plugin.
  149. For an example of the various ways one can swap scenes around at runtime,
  150. please see the :ref:`"Change scenes manually" <doc_change_scenes_manually>`
  151. documentation.