how to detect a signal from one instanced node with another instanced node?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By balaazs

player.gd:
@onready var raycast = $Raycast2D if Input.is_action_just_pressed("lmb"): if raycast.is_colliding(): emit_signal("HIT", raycast.get_collider())

target.gd
@onready var player = $"../player" func _ready(): player.HIT.connect(_on_hit) func _on_hit(obj): if obj == self: #do stuff

target and player are both children of the same parent node
sorry i have trouble using the formatting

:bust_in_silhouette: Reply From: godot_dev_

A related question to connecting signals to instanced object (its for Godot 3) can be found here and may be helpful to you

I haven’t worked with Godot 4 (so my syntax may be incorrect below although the idea should be applicable), but from reading the documentation on signal handling, I think a way you can solve your issue is by having the parent get a reference to both its children and then connect them together as follows

#parent.gd (Godot 4)
func _ready():
    var player = $"player"
    var target = $"target"
    player.HIT.connect(target._on_hit)
#parent.gd (Godot 3)
func _ready():
    var player = $"player"
    var target = $"target"
    player.connect("HIT",target,"_on_hit")

The idea is having the parents do the signal connecting, so that create modularity in your design. The children nodes don’t have to worry about the scene tree’s structure, they just need to emit signals at the appropriate time and provide an API (function) to handle signals from other nodes