Godot 通知

Godot 中的每个对象都实现了 _notification 方法。其目的是允许对象响应可能与之相关的各种引擎级回调。例如,如果引擎想让某个 CanvasItem 去执行“绘制”(draw)操作,它就会去调用 _notification(NOTIFICATION_DRAW)

在所有这些通知之中,有很多类似“绘制”这样经常需要在脚本中去覆盖的通知,多到 Godot 要提供专用函数的地步:

  • _ready() : NOTIFICATION_READY

  • _enter_tree() : NOTIFICATION_ENTER_TREE

  • _exit_tree() : NOTIFICATION_EXIT_TREE

  • _process(delta) : NOTIFICATION_PROCESS

  • _physics_process(delta) : NOTIFICATION_PHYSICS_PROCESS

  • _draw() : NOTIFICATION_DRAW

用户可能不会意识到 Node 之外的类型也有通知:

而且, 在节点中 确实 存在许多回调, 都没有任何专用方法, 但是它们仍然非常有用.

您可以从通用的 _notification 方法, 访问所有这些自定义通知.

备注

文档中被标记为“virtual”的方法(虚方法)是为使用脚本覆盖准备的。

一个经典的例子是 Object 中的 _init 方法. 虽然它没有等效的 NOTIFICATION_*, 但是引擎仍然调用该方法. 大多数语言(C#除外)都将其用作构造函数.

那么, 在哪种情况下应该使用这些通知或虚函数呢?

_process vs. _physics_process vs. *_input

当需要帧之间依赖于帧速率的 deltatime 时, 请使用 _process. 如果更新对象数据的代码, 需要尽可能频繁地更新, 那么这是正确放置这些代码的地方. 经常在这里执行循环逻辑检查和数据缓存, 但它取决于需要更新估算的频率. 如果他们不需要执行每一帧, 那么执行一个 Timer-yield-timeout 循环是另一种选择.

# Infinitely loop, but only execute whenever the Timer fires.
# Allows for recurring operations that don't trigger script logic
# every frame (or even every fixed frame).
while true:
    my_method()
    $Timer.start()
    yield($Timer, "timeout")

当一个帧之间需要独立于帧速率的 deltatime 时, 请使用 _physics_process. 如果不管时间是快还是慢, 代码需要随着时间的推移进行一致的更新, 那么这是正确的放置这些代码的地方. 重复的运动学和对象变换操作, 应在此处执行.

为了获得最佳性能, 应尽可能避免在这些回调期间, 进行输入检查. _process_physics_process 将在每个机会触发(默认情况下它们不会 休息). 相反, *_input 回调仅在, 引擎实际检测到输入的帧上触发.

可以同样检查输入回调中的输入动作. 如果要使用增量时间, 则可以根据需要从相关的增量时间方法中获取它.

# 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 vs. 初始化 vs. export

如果脚本初始化它自己的节点子树, 没有场景, 代码应该在这里执行. 其他属性或独立于 SceneTreeinitialization 也应在此处运行. 这会在 _ready_enter_tree 之前触发, 但是会在脚本创建并初始化其属性之后触发.

脚本具有三种可能在实例化过程中发生的属性分配方法:

# "one" is an "initialized value". These DO NOT trigger the setter.
# If someone set the value as "two" from the Inspector, this would be an
# "exported value". These DO trigger the setter.
export(String) var test = "one" setget set_test

func _init():
    # "three" is an "init assignment value".
    # These DO NOT trigger the setter, but...
    test = "three"
    # These DO trigger the setter. Note the `self` prefix.
    self.test = "three"

func set_test(value):
    test = value
    print("Setting: ", test)

当实例化一个场景时, 将根据以下顺序设置属性值:

  1. 初始值分配:实例化将先赋初值 initialization 或在 _init 方法中赋值。_init 赋值优先级高于 initialization 初值。

  2. 导出值赋值:如果从一个场景而不是脚本中实例化,Godot 将用导出的值替换脚本中定义的初始值。

因此,实例化脚本和场景,将影响初始化 引擎调用 setter 的次数.

_ready vs. _enter_tree vs. NOTIFICATION_PARENTED

当实例化连接到第一个执行场景的场景时,Godot将实例化树下的节点(进行 _init 调用),并构建从根向下的树。这导致 _enter_tree 调用, 向下级联树。当树构建完成, 叶子节点调用 _ready. 一旦所有子节点都完成了对它们的子节点的调用,一个节点就会调用这个方法。然后, 这将导致反向级联回到树的根部.

当实例化脚本或独立的场景时,节点不会在创建时被添加到SceneTree中,所以未触发 _enter_tree 回调。而只有 _init 调用发生。当场景被添加到SceneTree时, _enter_tree_ready 调用会发生。

如果需要触发作为节点设置父级到另一个节点而发生的行为, 无论它是否作为在主要/活动场景中的部分发生, 都可以使用 PARENTED 通知. 例如, 这有一个将节点方法连接到其父节点上自定义信号, 而不会失败的代码段。对可能在运行时创建并以数据为中心的节点很有用。

extends Node

var parent_cache

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

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

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