logic_preferences.rst 8.0 KB

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