Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
可覆寫函式
Godot 的 Node 類別提供可覆寫的虛擬函式,你可以透過這些函式在每個影格或特定事件(例如節點進入場景樹時)對節點進行更新。
本文件介紹你最常用到的這些函式。
也參考
這些函式在底層是依靠 Godot 的通知系統運作。想進一步瞭解,請參閱 Godot 通知。
除了類別的建構子外,還有兩個函式可用來初始化並取得節點:_enter_tree() 與 _ready()。
當節點進入場景樹時,會變為啟用狀態,且引擎會呼叫其 _enter_tree() 方法。此時該節點的子節點可能還不是活動場景的一部分。由於你可以隨時將節點移除並重新加回場景樹,因此這個函式在節點的生命週期中可能被呼叫多次。
多數情況下你會使用 _ready()。此函式只會在節點生命週期中被呼叫一次,且發生在 _enter_tree() 之後。_ready() 可以保證所有子節點都已進入場景樹,因此你可以安全地對它們呼叫 get_node()。
也參考
如需瞭解更多關於取得節點參照的內容,請閱讀 節點與場景實體。
另一個相關的回呼函式是 _exit_tree(),引擎會在節點即將離開場景樹時呼叫它。這可能發生於你呼叫 Node.remove_child() 或釋放節點時。
# Called every time the node enters the scene tree.
func _enter_tree():
pass
# Called when both the node and its children have entered the scene tree.
func _ready():
pass
# Called when the node is about to leave the scene tree, after all its
# children received the _exit_tree() callback.
func _exit_tree():
pass
// Called every time the node enters the scene tree.
public override void _EnterTree()
{
base._EnterTree();
}
// Called when both the node and its children have entered the scene tree.
public override void _Ready()
{
base._Ready();
}
// Called when the node is about to leave the scene tree, after all its
// children.
public override void _ExitTree()
{
base._ExitTree();
}
虛擬函式 _process() 與 _physics_process() 分別讓你在每個影格或每個物理影格對節點進行更新。更多資訊請參閱專門文件:空閒處理與物理處理。
# Called every frame.
func _process(delta):
pass
# Called every physics frame.
func _physics_process(delta):
pass
public override void _Process(double delta)
{
// Called every frame.
base._Process(delta);
}
public override void _PhysicsProcess(double delta)
{
// Called every physics frame.
base._PhysicsProcess(delta);
}
還有兩個非常重要的內建節點回呼函式:Node._unhandled_input() 與 Node._input(),你可以用來接收並處理各種輸入事件。_unhandled_input() 會接收所有尚未被 _input() 回呼或 UI 元件處理過的鍵盤、滑鼠等事件,通常用於遊戲流程中對玩家輸入的反應。而 _input() 則可以在這些事件傳遞給 _unhandled_input() 之前攔截並處理它們。
想進一步瞭解 Godot 輸入系統,請參閱 輸入章節。
# Called once for every event.
func _unhandled_input(event):
pass
# Called once for every event before _unhandled_input(), allowing you to
# consume some events.
func _input(event):
pass
// Called once for every event.
public override void _UnhandledInput(InputEvent @event)
{
base._UnhandledInput(@event);
}
// Called once for every event before _UnhandledInput(), allowing you to
// consume some events.
public override void _Input(InputEvent @event)
{
base._Input(@event);
}
還有一些其他可覆寫的函式,例如 Node._get_configuration_warnings()。特定節點型別也會提供更多回呼,例如 CanvasItem._draw() 可用於程式化繪圖,或 Control._gui_input() 用來處理 UI 元素上的點擊與輸入。