1. 程式人生 > >可覆寫的函數與創建節點

可覆寫的函數與創建節點

roc tab inactive mes classes 手動 bec contain 類型

以下所描述的這些可覆寫的函數,能夠應用於節點:

GDScript
func _enter_tree():
    # When the node enters the _Scene Tree_, it becomes active
    # and  this function is called. Children nodes have not entered
    # the active scene yet. In general, it‘s better to use _ready()
    # for most cases.
    pass

func _ready():
    # This function is called after _enter_tree, but it ensures
    # that all children nodes have also entered the _Scene Tree_,
    # and became active.
    pass

func _exit_tree():
    # When the node exits the _Scene Tree_, this function is called.
    # Children nodes have all exited the _Scene Tree_ at this point
    # and all became inactive.
    pass

func _process(delta):
    # This function is called every frame.
    pass

func _physics_process(delta):
    # This is called every physics frame.
    pass

如前所訴,用這些函數替代通知系統是更好的選擇。

創建節點

如果要用代碼方式創建一個節點, 只需調用 .new() 方法即可,這也適用於其他的基於類的數據類型。舉例說明:

GDScript
var s
func _ready():
    s = Sprite.new() # Create a new sprite!
    add_child(s) # Add it as a child of this node.

若要刪除一個節點,無論其是否在場景樹之內, free() 方法一定會被調用:

GDScript
func _someaction():
    s.free() # Immediately removes the node from the scene and frees it.

當一個節點被釋放時, 它也會釋放其所有子節點。因此, 手動刪除節點比看起來簡單得多。釋放基節點, 那麽子樹中的其他所有東西都會隨之消失。

當我們要刪除一個當前處於“阻塞”狀態的節點時,就可能發生這種情況, 因為此時它正在發出信號或者在調用一個函數。這會導致遊戲崩潰。使用調試器運行Godot通常能捕獲這種情況並向你發出警告。

刪除一個節點最安全的方法是使用 Node.queue_free()。這會在程序空閑時安全地擦除該節點。

GDScript
func _someaction():
    s.queue_free() # Removes the node from the scene and frees it when it becomes safe to do so.

可覆寫的函數與創建節點