logic_preferences.rst 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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(PackedScene) var a_building = 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. Preloading allows the script to handle all the loading the moment one loads the
  81. script. Preloading is useful, but there are also times when one doesn't wish
  82. for it. To distinguish these situations, there are a few things one can
  83. consider:
  84. 1. If one cannot determine when the script might load, then preloading a
  85. resource, especially a scene or script, could result in further loads one
  86. does not expect. This could lead to unintentional, variable-length
  87. load times on top of the original script's load operations.
  88. 2. If something else could replace the value (like a scene's exported
  89. initialization), then preloading the value has no meaning. This point isn't
  90. a significant factor if one intends to always create the script on its own.
  91. 3. If one wishes only to 'import' another class resource (script or scene),
  92. then using a preloaded constant is often the best course of action. However,
  93. in exceptional cases, one may wish not to do this:
  94. 1. If the 'imported' class is liable to change, then it should be a property
  95. instead, initialized either using an ``export`` or a ``load()`` (and
  96. perhaps not even initialized until later).
  97. 2. If the script requires a great many dependencies, and one does not wish
  98. to consume so much memory, then one may wish to, load and unload various
  99. dependencies at runtime as circumstances change. If one preloads
  100. resources into constants, then the only way to unload these resources
  101. would be to unload the entire script. If they are instead loaded
  102. properties, then one can set them to ``null`` and remove all references
  103. to the resource entirely (which, as a
  104. :ref:`RefCounted <class_RefCounted>`-extending type, will cause the
  105. resources to delete themselves from memory).
  106. Large levels: static vs. dynamic
  107. --------------------------------
  108. If one is creating a large level, which circumstances are most appropriate?
  109. Should they create the level as one static space? Or should they load the
  110. level in pieces and shift the world's content as needed?
  111. Well, the simple answer is, "when the performance requires it." The
  112. dilemma associated with the two options is one of the age-old programming
  113. choices: does one optimize memory over speed, or vice versa?
  114. The naive answer is to use a static level that loads everything at once.
  115. But, depending on the project, this could consume a large amount of
  116. memory. Wasting users' RAM leads to programs running slow or outright
  117. crashing from everything else the computer tries to do at the same time.
  118. No matter what, one should break larger scenes into smaller ones (to aid
  119. in reusability of assets). Developers can then design a node that manages the
  120. creation/loading and deletion/unloading of resources and nodes in real-time.
  121. Games with large and varied environments or procedurally generated
  122. elements often implement these strategies to avoid wasting memory.
  123. On the flip side, coding a dynamic system is more complex, i.e. uses more
  124. programmed logic, which results in opportunities for errors and bugs. If one
  125. isn't careful, they can develop a system that bloats the technical debt of
  126. the application.
  127. As such, the best options would be...
  128. 1. To use a static level for smaller games.
  129. 2. If one has the time/resources on a medium/large game, create a library or
  130. plugin that can code the management of nodes and resources. If refined
  131. over time, so as to improve usability and stability, then it could evolve
  132. into a reliable tool across projects.
  133. 3. Code the dynamic logic for a medium/large game because one has the coding
  134. skills, but not the time or resources to refine the code (game's
  135. gotta get done). Could potentially refactor later to outsource the code
  136. into a plugin.
  137. For an example of the various ways one can swap scenes around at runtime,
  138. please see the :ref:`"Change scenes manually" <doc_change_scenes_manually>`
  139. documentation.