godot_notifications.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. .. _doc_godot_notifications:
  2. Godot notifications
  3. ===================
  4. Every Object in Godot implements a
  5. :ref:`_notification <class_Object_private_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_private_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. .. code-tab:: csharp
  64. using Godot;
  65. public partial class MyNode : Node
  66. {
  67. // Allows for recurring operations that don't trigger script logic
  68. // every frame (or even every fixed frame).
  69. public override void _Ready()
  70. {
  71. var timer = new Timer();
  72. timer.Autostart = true;
  73. timer.WaitTime = 0.5;
  74. AddChild(timer);
  75. timer.Timeout += () => GD.Print("This block runs every 0.5 seconds");
  76. }
  77. }
  78. Use ``_physics_process()`` when one needs a framerate-independent delta time
  79. between frames. If code needs consistent updates over time, regardless
  80. of how fast or slow time advances, this is the right place.
  81. Recurring kinematic and object transform operations should execute here.
  82. While it is possible, to achieve the best performance, one should avoid
  83. making input checks during these callbacks. ``_process()`` and
  84. ``_physics_process()`` will trigger at every opportunity (they do not "rest" by
  85. default). In contrast, ``*_input()`` callbacks will trigger only on frames in
  86. which the engine has actually detected the input.
  87. One can check for input actions within the input callbacks just the same.
  88. If one wants to use delta time, one can fetch it from the related
  89. delta time methods as needed.
  90. .. tabs::
  91. .. code-tab:: gdscript GDScript
  92. # Called every frame, even when the engine detects no input.
  93. func _process(delta):
  94. if Input.is_action_just_pressed("ui_select"):
  95. print(delta)
  96. # Called during every input event.
  97. func _unhandled_input(event):
  98. match event.get_class():
  99. "InputEventKey":
  100. if Input.is_action_just_pressed("ui_accept"):
  101. print(get_process_delta_time())
  102. .. code-tab:: csharp
  103. using Godot;
  104. public partial class MyNode : Node
  105. {
  106. // Called every frame, even when the engine detects no input.
  107. public void _Process(double delta)
  108. {
  109. if (Input.IsActionJustPressed("ui_select"))
  110. GD.Print(delta);
  111. }
  112. // Called during every input event. Equally true for _input().
  113. public void _UnhandledInput(InputEvent @event)
  114. {
  115. switch (@event)
  116. {
  117. case InputEventKey:
  118. if (Input.IsActionJustPressed("ui_accept"))
  119. GD.Print(GetProcessDeltaTime());
  120. break;
  121. }
  122. }
  123. }
  124. _init vs. initialization vs. export
  125. -----------------------------------
  126. If the script initializes its own node subtree, without a scene,
  127. that code should execute in ``_init()``. Other property or SceneTree-independent
  128. initializations should also run here.
  129. .. note::
  130. The C# equivalent to GDScript's ``_init()`` method is the constructor.
  131. ``_init()`` triggers before ``_enter_tree()`` or ``_ready()``, but after a script
  132. creates and initializes its properties. When instantiating a scene, property
  133. values will set up according to the following sequence:
  134. 1. **Initial value assignment:** the property is assigned its initialization value,
  135. or its default value if one is not specified. If a setter exists, it is not used.
  136. 2. **``_init()`` assignment:** the property's value is replaced by any assignments
  137. made in ``_init()``, triggering the setter.
  138. 3. **Exported value assignment:** an exported property's value is again replaced by
  139. any value set in the Inspector, triggering the setter.
  140. .. tabs::
  141. .. code-tab:: gdscript GDScript
  142. # test is initialized to "one", without triggering the setter.
  143. @export var test: String = "one":
  144. set(value):
  145. test = value + "!"
  146. func _init():
  147. # Triggers the setter, changing test's value from "one" to "two!".
  148. test = "two"
  149. # If someone sets test to "three" from the Inspector, it would trigger
  150. # the setter, changing test's value from "two!" to "three!".
  151. .. code-tab:: csharp
  152. using Godot;
  153. public partial class MyNode : Node
  154. {
  155. private string _test = "one";
  156. [Export]
  157. public string Test
  158. {
  159. get { return _test; }
  160. set { _test = $"{value}!"; }
  161. }
  162. public MyNode()
  163. {
  164. // Triggers the setter, changing _test's value from "one" to "two!".
  165. Test = "two";
  166. }
  167. // If someone sets Test to "three" in the Inspector, it would trigger
  168. // the setter, changing _test's value from "two!" to "three!".
  169. }
  170. As a result, instantiating a script versus a scene may affect both the
  171. initialization *and* the number of times the engine calls the setter.
  172. _ready vs. _enter_tree vs. NOTIFICATION_PARENTED
  173. ------------------------------------------------
  174. When instantiating a scene connected to the first executed scene, Godot will
  175. instantiate nodes down the tree (making ``_init()`` calls) and build the tree
  176. going downwards from the root. This causes ``_enter_tree()`` calls to cascade
  177. down the tree. Once the tree is complete, leaf nodes call ``_ready``. A node
  178. will call this method once all child nodes have finished calling theirs. This
  179. then causes a reverse cascade going up back to the tree's root.
  180. When instantiating a script or a standalone scene, nodes are not
  181. added to the SceneTree upon creation, so no ``_enter_tree()`` callbacks
  182. trigger. Instead, only the ``_init()`` call occurs. When the scene is added
  183. to the SceneTree, the ``_enter_tree()`` and ``_ready()`` calls occur.
  184. If one needs to trigger behavior that occurs as nodes parent to another,
  185. regardless of whether it occurs as part of the main/active scene or not, one
  186. can use the :ref:`PARENTED <class_Node_constant_NOTIFICATION_PARENTED>` notification.
  187. For example, here is a snippet that connects a node's method to
  188. a custom signal on the parent node without failing. Useful on data-centric
  189. nodes that one might create at runtime.
  190. .. tabs::
  191. .. code-tab:: gdscript GDScript
  192. extends Node
  193. var parent_cache
  194. func connection_check():
  195. return parent_cache.has_user_signal("interacted_with")
  196. func _notification(what):
  197. match what:
  198. NOTIFICATION_PARENTED:
  199. parent_cache = get_parent()
  200. if connection_check():
  201. parent_cache.interacted_with.connect(_on_parent_interacted_with)
  202. NOTIFICATION_UNPARENTED:
  203. if connection_check():
  204. parent_cache.interacted_with.disconnect(_on_parent_interacted_with)
  205. func _on_parent_interacted_with():
  206. print("I'm reacting to my parent's interaction!")
  207. .. code-tab:: csharp
  208. using Godot;
  209. public partial class MyNode : Node
  210. {
  211. private Node _parentCache;
  212. public bool ConnectionCheck()
  213. {
  214. return _parentCache.HasUserSignal("InteractedWith");
  215. }
  216. public void _Notification(int what)
  217. {
  218. switch (what)
  219. {
  220. case NotificationParented:
  221. _parentCache = GetParent();
  222. if (ConnectionCheck())
  223. {
  224. _parentCache.Connect("InteractedWith", Callable.From(OnParentInteractedWith));
  225. }
  226. break;
  227. case NotificationUnparented:
  228. if (ConnectionCheck())
  229. {
  230. _parentCache.Disconnect("InteractedWith", Callable.From(OnParentInteractedWith));
  231. }
  232. break;
  233. }
  234. }
  235. private void OnParentInteractedWith()
  236. {
  237. GD.Print("I'm reacting to my parent's interaction!");
  238. }
  239. }