自定視覺腳本節點¶
可以使用 GDScript 撰寫自定節點,並於視覺腳本內使用。可以用來將複雜的程式碼移至 GDScript 中並重複使用。
建立自定節點¶
建立一個繼承 VisualScriptCustomNode 的新腳本,並在腳本最上方加上 tool
關鍵字。需要加上 tool 是因為要讓腳本能在編輯器中執行。
有一些能實作來設定自定節點參數的函式。只需要在有必要時加上函式就好了,舉例來說,若 _has_input_sequence_port
應該回傳 false
的話就不需要實作。
自定節點中最重要的部分就是 _step
函式。節點的邏輯就定義在 _step 中。
inputs
參數包含了輸入連接埠的值。
outputs
參數為一個陣列,其中的索引值代表輸出的連接埠 ID。可以修改 outputs 來設定輸出連接埠的值。
start_mode
可以用來確認是否為第一次呼叫 _step
。
working_mem
在各個 _step
間保持不變。可以用來儲存資訊。
若想拋出錯誤,如輸入類型不正確時,可以回傳字串格式的錯誤訊息。若沒問題的話,則回傳下一個要呼叫的序列埠 ID。若自定節點沒有下一個要呼叫的節點的話,則回傳 0。
範例:
tool
extends VisualScriptCustomNode
# The name of the custom node as it appears in the search.
func _get_caption():
return "Get Input Direction 2D"
func _get_category():
return "Input"
# The text displayed after the input port / sequence arrow.
func _get_text():
return ""
func _get_input_value_port_count():
return 0
# The types of the inputs per index starting from 0.
func _get_input_value_port_type(idx):
return TYPE_OBJECT
func _get_output_value_port_count():
return 1
# The types of outputs per index starting from 0.
func _get_output_value_port_type(idx):
return TYPE_VECTOR2
# The text displayed before each output node per index.
func _get_output_value_port_name(idx):
return "Direction"
func _has_input_sequence_port():
return true
# The number of output sequence ports to use
# (has to be at least one if you have an input sequence port).
func _get_output_sequence_port_count():
return 1
func _step(inputs, outputs, start_mode, working_mem):
# start_mode can be checked to see if it is the first time _step is called.
# This is useful if you only want to do an operation once.
# working_memory is persistent between _step calls.
# The inputs array contains the value of the input ports.
var x = int(Input.is_action_pressed("ui_right")) - int(Input.is_action_pressed("ui_left"))
var y = int(Input.is_action_pressed("ui_down")) - int(Input.is_action_pressed("ui_up"))
# The outputs array is used to set the data of the output ports.
outputs[0] = Vector2(x, y)
# Return the error string if an error occurred, else the id of the next sequence port.
return 0
使用自定節點¶
要使用自定節點腳本,新增一個 CustomNode
,選擇 CustomNode 並將節點腳本拖移至屬性面板中的 script
屬性中。

結果:
