godot_notifications.rst 10 KB

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