Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Сповіщення Godot

Кожен Об'єкт у Godot реалізує метод _notification. Його мета - дозволити об'єкту реагувати на різноманітні зворотні виклики на рівні рушія, які можуть мати до нього відношення. Наприклад, якщо рушій скаже CanvasItem "намалювати", він викличе _notification(NOTIFICATION_DRAW).

Деякі з цих сповіщень, наприклад, малювання (draw), корисно замінити у скриптах. Настільки, що Godot поставляє багатьох із них зі спеціальними функціями:

  • _ready(): ПОВІДОМЛЕННЯ_ГОТОВЕ

  • _enter_tree(): NOTIFICATION_ENTER_TREE

  • _exit_tree() : ДЕРЕВО_ВИХОДУ_ПОВІДОМЛЕННЯ

  • _process(delta) : ПРОЦЕС_ПОВІДОМЛЕННЯ

  • _physics_process(delta): ПОВІДОМЛЕННЯ_ФІЗИЧНОГО_ПРОЦЕСУ

  • _draw() : ПОВІДОМЛЕННЯ

Користувачі можуть не розуміти, що сповіщення існують і для інших типів, окрім, наприклад, Node:

  • Object::NOTIFICATION_POSTINITIALIZE: зворотний виклик, який спрацьовує під час ініціалізації об’єкта. Не доступний для скриптів.

  • Object::NOTIFICATION_PREDELETE: зворотний виклик, який спрацьовує перед тим, як рушій видалить об'єкт, тобто "деструктор".

І багато зворотних викликів, які існують у вузлах, не мають спеціальних методів, але все ще є досить корисними.

  • Node::NOTIFICATION_PARENTED: зворотний виклик, який запускається щоразу, коли один додає дочірній вузол до іншого вузла.

  • Node::NOTIFICATION_UNPARENTED: зворотний виклик, який запускається в будь-який час, коли один видаляє дочірній вузол з іншого вузла.

Доступ до всіх цих кастомних сповіщень можна отримати за допомогою універсального методу _notification().

Примітка

Методи в документації, позначені як "virtual" (віртуальні), також призначені для перевизначення у скриптах.

Класичним прикладом є метод _init в Object. Хоча він не має еквівалента NOTIFICATION_*, рушій все одно викликає цей метод. Більшість мов (крім C#) використовують його як конструктор.

Отже, в якій ситуації слід використовувати кожне з цих сповіщень або віртуальні функції?

_process та _physics_process vs. *_input

Use _process() when one needs a framerate-dependent delta time between frames. If code that updates object data needs to update as often as possible, this is the right place. Recurring logic checks and data caching often execute here, but it comes down to the frequency at which one needs the evaluations to update. If they don't need to execute every frame, then implementing a Timer-timeout loop is another option.

# Allows for recurring operations that don't trigger script logic
# every frame (or even every fixed frame).
func _ready():
    var timer = Timer.new()
    timer.autostart = true
    timer.wait_time = 0.5
    add_child(timer)
    timer.timeout.connect(func():
        print("This block runs every 0.5 seconds")
    )

Use _physics_process() when one needs a framerate-independent delta time between frames. If code needs consistent updates over time, regardless of how fast or slow time advances, this is the right place. Recurring kinematic and object transform operations should execute here.

While it is possible, to achieve the best performance, one should avoid making input checks during these callbacks. _process() and _physics_process() will trigger at every opportunity (they do not "rest" by default). In contrast, *_input() callbacks will trigger only on frames in which the engine has actually detected the input.

One can check for input actions within the input callbacks just the same. If one wants to use delta time, one can fetch it from the related delta time methods as needed.

# Called every frame, even when the engine detects no input.
func _process(delta):
    if Input.is_action_just_pressed("ui_select"):
        print(delta)

# Called during every input event.
func _unhandled_input(event):
    match event.get_class():
        "InputEventKey":
            if Input.is_action_just_pressed("ui_accept"):
                print(get_process_delta_time())

_init, initialization та export

If the script initializes its own node subtree, without a scene, that code should execute in _init(). Other property or SceneTree-independent initializations should also run here.

Примітка

The C# equivalent to GDScript's _init() method is the constructor.

_init() triggers before _enter_tree() or _ready(), but after a script creates and initializes its properties. When instantiating a scene, property values will set up according to the following sequence:

  1. Initial value assignment: the property is assigned its initialization value, or its default value if one is not specified. If a setter exists, it is not used.

  2. ``_init()`` assignment: the property's value is replaced by any assignments made in _init(), triggering the setter.

  3. Exported value assignment: an exported property's value is again replaced by any value set in the Inspector, triggering the setter.

# test is initialized to "one", without triggering the setter.
@export var test: String = "one":
    set(value):
        test = value + "!"

func _init():
    # Triggers the setter, changing test's value from "one" to "two!".
    test = "two"

# If someone sets test to "three" from the Inspector, it would trigger
# the setter, changing test's value from "two!" to "three!".

As a result, instantiating a script versus a scene may affect both the initialization and the number of times the engine calls the setter.

_ready, _enter_tree та NOTIFICATION_PARENTED

When instantiating a scene connected to the first executed scene, Godot will instantiate nodes down the tree (making _init() calls) and build the tree going downwards from the root. This causes _enter_tree() calls to cascade down the tree. Once the tree is complete, leaf nodes call _ready. A node will call this method once all child nodes have finished calling theirs. This then causes a reverse cascade going up back to the tree's root.

When instantiating a script or a standalone scene, nodes are not added to the SceneTree upon creation, so no _enter_tree() callbacks trigger. Instead, only the _init() call occurs. When the scene is added to the SceneTree, the _enter_tree() and _ready() calls occur.

Якщо потрібно ініціювати поведінку, яка виникає як поведінка батьківського вузла до іншого, незалежно від того, відбувається вона як частина основної/активної сцени чи ні, можна використовувати сповіщення PARENTED. Наприклад, ось фрагмент, який підключає метод вузла до користувацького сигналу на батьківському вузлі без збоїв. Корисно для вузлів, орієнтованих на дані, які можна створити під час виконання.

extends Node

var parent_cache

func connection_check():
    return parent_cache.has_user_signal("interacted_with")

func _notification(what):
    match what:
        NOTIFICATION_PARENTED:
            parent_cache = get_parent()
            if connection_check():
                parent_cache.interacted_with.connect(_on_parent_interacted_with)
        NOTIFICATION_UNPARENTED:
            if connection_check():
                parent_cache.interacted_with.disconnect(_on_parent_interacted_with)

func _on_parent_interacted_with():
    print("I'm reacting to my parent's interaction!")