How to send a signal to single instance of a node?

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

So i have a player scene that have hidden menu , than when is that player turn, the menu should open. So i tried doing it by having a signal change the visibility of the player on the main battle scene. The problem is that all players have the same signal, so when the signal is emitted, menu from every single player instance is activating the menu.
On the battle script:

self.connect("myturn",unitlist[0],"_on_Hero_myturn")
emit_signal("myturn")

On the player script:

func _on_Hero_myturn():
	var menu
	if get_tree().get_nodes_in_group("Turn_Menu").size() >= 1:
		menu = get_tree().get_nodes_in_group("Turn_Menu")
	for i in menu:
		i.visible = !i.visible
:bust_in_silhouette: Reply From: njamster

You do not “send a signal to a[n] […] instance”. You emit it. And other nodes react to that emission. So if you write this into your script:

self.connect("myturn", unitlist[0], "_on_Hero_myturn")

whatever unitlist[0] is, it will call it’s method _on_Hero_myturn whenever your battle script emits its signal myturn. If you do this multiple times:

self.connect("myturn", unitlist[0], "_on_Hero_myturn")
self.connect("myturn", unitlist[1], "_on_Hero_myturn")

then both unitlist[0] and unitlist[1] will call their method _on_Hero_myturn whenever your battle script emits it’s signal myturn.

Now, if you want both units to be able to react to the same signal, but only one at a time, you need to define who is supposed to react and who isn’t via an argument:

battle-script

signal myturn(unit)

func _ready():
    emit_signal("myturn", unitlist[0])

player-script

func _on_Hero_myturn(unit):
    if self == unit:
        # react to it
    # else: do nothing

Thanks a lot! So i was only connecting to the one node and not all, but they are all reacting. It is because they are instances from the same node?

lukesheep | 2020-04-21 12:14

If unitlist[0] is one specific instance then only that once specific instance will be connected to the signal. If however the scene all your player-instances are based on includes code that connects to the battle-script, then yes, every instance will connect.

njamster | 2020-04-21 16:17