logic_preferences.rst 7.2 KB

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