Bunch of identical nodes, need to tell the main script who they are.

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

I have 31 TextureRects on a larger TextureRect, set manually in a 6 * 5 grid, plus a spare one. All I need to do is to have them respond when the mouse is clicked on them by telling the main script which one they are. Since they’re all identical in every other way and need to behave the same, they can all just use the same node signal (gui_input). But I can’t work out an efficient way that the signal would identify which one was clicked if they all just report back to the same script.

All I can think of is to set each signal manually and then jump to a function from there, but that would mean 31 of this…

func _on_1_gui_input(event):
	CheckClick(event,"1")

func _on_2_gui_input(event):
	CheckClick(event,"2")


func CheckClick(event, num):
	if event is InputEventMouseButton and event.button_index == BUTTON_LEFT and event.pressed:
# DO STUFF

Obviously this just goes against every rule of programming efficiently. There must be a simple way of doing this, either through groups or from the parent or something, but I’m being tired and dumb right now and can’t think of the solution.

:bust_in_silhouette: Reply From: kidscancode

Note: _gui_input() is not a signal. Put the same script on each TextureRect (they’re instances right?):

extends TextureRect

signal clicked

func _gui_input(event):
    if event is InputEventMouseButton and event.button_index == BUTTON_LEFT and event.pressed:
        emit_signal("clicked")

The node can pass a reference to itself along with the signal, so you only need one receiver function.

func _ready():
    for node in <whatever_parent_node>.get_children():
        node.connect("clicked", self, "CheckClick", [node])

func CheckClick(node):
    print("Clicked:", node.name)

Part of the problem is that they’re not instances. I need to place them manually because they’re not in a particular pattern. But if I do place them manually, then it looks like I have to manually attach scripts or node signals (they’re not the same as signals?) to each one, which is too ugly.

So I think I’ll have to note their position and have some kind of array to set them up as instances. Then I can do a solution such as yours above.

Thanks.

Farflame | 2019-06-04 23:05