godot_notifications.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. .. _doc_godot_notifications:
  2. Godot notifications
  3. ===================
  4. Every Object in Godot implements a
  5. :ref:`_notification <class_Object_method__notification>` method. Its purpose is to
  6. allow the Object to respond to a variety of engine-level callbacks that may
  7. relate to it. For example, if the engine tells a
  8. :ref:`CanvasItem <class_CanvasItem>` to "draw", it will call
  9. ``_notification(NOTIFICATION_DRAW)``.
  10. Some of these notifications, like draw, are useful to override in scripts. So
  11. much so that Godot exposes many of them with dedicated functions:
  12. - ``_ready()``: ``NOTIFICATION_READY``
  13. - ``_enter_tree()``: ``NOTIFICATION_ENTER_TREE``
  14. - ``_exit_tree()``: ``NOTIFICATION_EXIT_TREE``
  15. - ``_process(delta)``: ``NOTIFICATION_PROCESS``
  16. - ``_physics_process(delta)``: ``NOTIFICATION_PHYSICS_PROCESS``
  17. - ``_draw()``: ``NOTIFICATION_DRAW``
  18. What users might *not* realize is that notifications exist for types other
  19. than Node alone, for example:
  20. - :ref:`Object::NOTIFICATION_POSTINITIALIZE <class_Object_constant_NOTIFICATION_POSTINITIALIZE>`:
  21. a callback that triggers during object initialization. Not accessible to scripts.
  22. - :ref:`Object::NOTIFICATION_PREDELETE <class_Object_constant_NOTIFICATION_PREDELETE>`:
  23. a callback that triggers before the engine deletes an Object, i.e. a
  24. "destructor".
  25. And many of the callbacks that *do* exist in Nodes don't have any dedicated
  26. methods, but are still quite useful.
  27. - :ref:`Node::NOTIFICATION_PARENTED <class_Node_constant_NOTIFICATION_PARENTED>`:
  28. a callback that triggers anytime one adds a child node to another node.
  29. - :ref:`Node::NOTIFICATION_UNPARENTED <class_Node_constant_NOTIFICATION_UNPARENTED>`:
  30. a callback that triggers anytime one removes a child node from another
  31. node.
  32. One can access all these custom notifications from the universal
  33. ``_notification()`` method.
  34. .. note::
  35. Methods in the documentation labeled as "virtual" are also intended to be
  36. overridden by scripts.
  37. A classic example is the
  38. :ref:`_init <class_Object_method__init>` method in Object. While it has no
  39. ``NOTIFICATION_*`` equivalent, the engine still calls the method. Most languages
  40. (except C#) rely on it as a constructor.
  41. So, in which situation should one use each of these notifications or
  42. virtual functions?
  43. _process vs. _physics_process vs. \*_input
  44. ------------------------------------------
  45. Use ``_process()`` when one needs a framerate-dependent delta time between
  46. frames. If code that updates object data needs to update as often as
  47. possible, this is the right place. Recurring logic checks and data caching
  48. often execute here, but it comes down to the frequency at which one needs
  49. the evaluations to update. If they don't need to execute every frame, then
  50. implementing a Timer-timeout loop is another option.
  51. .. tabs::
  52. .. code-tab:: gdscript GDScript
  53. # Allows for recurring operations that don't trigger script logic
  54. # every frame (or even every fixed frame).
  55. func _ready():
  56. var timer = Timer.new()
  57. timer.autostart = true
  58. timer.wait_time = 0.5
  59. add_child(timer)
  60. timer.timeout.connect(func():
  61. print("This block runs every 0.5 seconds")
  62. )
  63. Use ``_physics_process()`` when one needs a framerate-independent delta time
  64. between frames. If code needs consistent updates over time, regardless
  65. of how fast or slow time advances, this is the right place.
  66. Recurring kinematic and object transform operations should execute here.
  67. While it is possible, to achieve the best performance, one should avoid
  68. making input checks during these callbacks. ``_process()`` and
  69. ``_physics_process()`` will trigger at every opportunity (they do not "rest" by
  70. default). In contrast, ``*_input()`` callbacks will trigger only on frames in
  71. which the engine has actually detected the input.
  72. One can check for input actions within the input callbacks just the same.
  73. If one wants to use delta time, one can fetch it from the related
  74. delta time methods as needed.
  75. .. tabs::
  76. .. code-tab:: gdscript GDScript
  77. # Called every frame, even when the engine detects no input.
  78. func _process(delta):
  79. if Input.is_action_just_pressed("ui_select"):
  80. print(delta)
  81. # Called during every input event.
  82. func _unhandled_input(event):
  83. match event.get_class():
  84. "InputEventKey":
  85. if Input.is_action_just_pressed("ui_accept"):
  86. print(get_process_delta_time())
  87. .. code-tab:: csharp
  88. using Godot;
  89. public partial class MyNode : Node
  90. {
  91. // Called every frame, even when the engine detects no input.
  92. public void _Process(double delta)
  93. {
  94. if (Input.IsActionJustPressed("ui_select"))
  95. GD.Print(delta);
  96. }
  97. // Called during every input event. Equally true for _input().
  98. public void _UnhandledInput(InputEvent @event)
  99. {
  100. switch (@event)
  101. {
  102. case InputEventKey:
  103. if (Input.IsActionJustPressed("ui_accept"))
  104. GD.Print(GetProcessDeltaTime());
  105. break;
  106. }
  107. }
  108. }
  109. _init vs. initialization vs. export
  110. -----------------------------------
  111. If the script initializes its own node subtree, without a scene,
  112. that code should execute here. Other property or SceneTree-independent
  113. initializations should also run here. This triggers before ``_ready()`` or
  114. ``_enter_tree()``, but after a script creates and initializes its properties.
  115. Scripts have three types of property assignments that can occur during
  116. instantiation:
  117. .. tabs::
  118. .. code-tab:: gdscript GDScript
  119. # "one" is an "initialized value". These DO NOT trigger the setter.
  120. # If someone set the value as "two" from the Inspector, this would be an
  121. # "exported value". These DO trigger the setter.
  122. export(String) var test = "one" setget set_test
  123. func _init():
  124. # "three" is an "init assignment value".
  125. # These DO NOT trigger the setter, but...
  126. test = "three"
  127. # These DO trigger the setter. Note the `self` prefix.
  128. self.test = "three"
  129. func set_test(value):
  130. test = value
  131. print("Setting: ", test)
  132. .. code-tab:: csharp
  133. using Godot;
  134. public partial class MyNode : Node
  135. {
  136. private string _test = "one";
  137. // Changing the value from the inspector does trigger the setter in C#.
  138. [Export]
  139. public string Test
  140. {
  141. get { return _test; }
  142. set
  143. {
  144. _test = value;
  145. GD.Print($"Setting: {_test}");
  146. }
  147. }
  148. public MyNode()
  149. {
  150. // Triggers the setter as well
  151. Test = "three";
  152. }
  153. }
  154. When instantiating a scene, property values will set up according to the
  155. following sequence:
  156. 1. **Initial value assignment:** instantiation will assign either the
  157. initialization value or the init assignment value. Init assignments take
  158. priority over initialization values.
  159. 2. **Exported value assignment:** If instancing from a scene rather than
  160. a script, Godot will assign the exported value to replace the initial
  161. value defined in the script.
  162. As a result, instantiating a script versus a scene will affect both the
  163. initialization *and* the number of times the engine calls the setter.
  164. _ready vs. _enter_tree vs. NOTIFICATION_PARENTED
  165. ------------------------------------------------
  166. When instantiating a scene connected to the first executed scene, Godot will
  167. instantiate nodes down the tree (making ``_init()`` calls) and build the tree
  168. going downwards from the root. This causes ``_enter_tree()`` calls to cascade
  169. down the tree. Once the tree is complete, leaf nodes call ``_ready``. A node
  170. will call this method once all child nodes have finished calling theirs. This
  171. then causes a reverse cascade going up back to the tree's root.
  172. When instantiating a script or a standalone scene, nodes are not
  173. added to the SceneTree upon creation, so no ``_enter_tree()`` callbacks
  174. trigger. Instead, only the ``_init()`` call occurs. When the scene is added
  175. to the SceneTree, the ``_enter_tree()`` and ``_ready()`` calls occur.
  176. If one needs to trigger behavior that occurs as nodes parent to another,
  177. regardless of whether it occurs as part of the main/active scene or not, one
  178. can use the :ref:`PARENTED <class_Node_constant_NOTIFICATION_PARENTED>` notification.
  179. For example, here is a snippet that connects a node's method to
  180. a custom signal on the parent node without failing. Useful on data-centric
  181. nodes that one might create at runtime.
  182. .. tabs::
  183. .. code-tab:: gdscript GDScript
  184. extends Node
  185. var parent_cache
  186. func connection_check():
  187. return parent_cache.has_user_signal("interacted_with")
  188. func _notification(what):
  189. match what:
  190. NOTIFICATION_PARENTED:
  191. parent_cache = get_parent()
  192. if connection_check():
  193. parent_cache.interacted_with.connect(_on_parent_interacted_with)
  194. NOTIFICATION_UNPARENTED:
  195. if connection_check():
  196. parent_cache.interacted_with.disconnect(_on_parent_interacted_with)
  197. func _on_parent_interacted_with():
  198. print("I'm reacting to my parent's interaction!")
  199. .. code-tab:: csharp
  200. using Godot;
  201. public partial class MyNode : Node
  202. {
  203. private Node _parentCache;
  204. public void ConnectionCheck()
  205. {
  206. return _parentCache.HasUserSignal("InteractedWith");
  207. }
  208. public void _Notification(int what)
  209. {
  210. switch (what)
  211. {
  212. case NotificationParented:
  213. _parentCache = GetParent();
  214. if (ConnectionCheck())
  215. {
  216. _parentCache.Connect("InteractedWith", Callable.From(OnParentInteractedWith));
  217. }
  218. break;
  219. case NotificationUnparented:
  220. if (ConnectionCheck())
  221. {
  222. _parentCache.Disconnect("InteractedWith", Callable.From(OnParentInteractedWith));
  223. }
  224. break;
  225. }
  226. }
  227. private void OnParentInteractedWith()
  228. {
  229. GD.Print("I'm reacting to my parent's interaction!");
  230. }
  231. }