godot_notifications.rst 10 KB

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