Godot: Call down, signal up.
> If a node is calling a child (i.e. going “down” the tree), then get_node() is appropriate.
> If a node needs to communicate “up” the tree, it should probably use a signal.
> If you keep this rule in mind when designing your scene setup, you’ll be well on your way to a maintainable, well-organized project. And you’ll avoid using the cumbersome node paths that lead to problems.
親から子への流れでは、get_node() などで calling child をするのが基本
逆に、子から親など上方向へ処理を流したい場合は、signal を使うのが基本となる
他の方法としては、以下がある
groups を使う
groups はタグ付け機能
例えば、 enemies
group でタグ付けをして、bomb 使用時に get_nodes_in_group
で enemies のみを対象に処理をしたり、以下のコードでは直接任意のメソッドを実行できる
get_tree().call_group("enemies", "explode")
owner を使う
階層が深い場合は、owner プロパティを使うとルートノードまで参照を飛ばすことができる
ルートの CenterContiner で Button が押された時の関数を用意しておいて
gdextends CenterContainer
func _on_button_pressed(button_name):
print(button_name, " was pressed")
深い階層下のボタンでは、owner に対して signal をコネクトして emit をする
gdextends Button
func _ready():
connect("pressed", owner, "_on_button_pressed", [name])
owner が変わらない限りは、階層構造は崩れない。(../../ のような参照の仕方よりかはマシって感じ)