Connecting to multiple instances

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Jambers
:warning: Old Version Published before Godot 3 was released.

I have a button that creates multiple instances of “ship”,

    var ship_create = ship.instance()
    ship_location=Vector2(randi()%1335,randi()%751)
    get_node("ship_node").add_child(ship_create)
    ship_create.set_global_pos(ship_location)

I have another button that instances of “yellow_sprite” and tries to connect them to the ships’ area_enter flag.

func _ready():
	set_process(true)
	get_node("../../ship_node/ship").connect("area_enter",self,"_on_ship_body_enter")

The yellow sprites only connect to the first ship that is created. Is there a way to connect to all ships that are created?

The reason this is happening is because every ship gets a unique name when it is instanced - only the first ship is called “ship”. While the game is running, if you click “debugger” along the bottom, then go to the “Remote Inspector” tab and look at the “live scene tree” you’ll see that their names are probably something like:
ship
@ship@2
@ship@3
@ship@4

I’ll write a full answer, but first I need to understand your problem a little bit better. Does the second button create one “yellowsprite”, or multiple "yellowsprite"s - like one for each ship? If you could tell me what “yellowsprite” was meant to be, that may help as well.

keke | 2017-07-04 02:22

Thanks for the reply!

The second button continuously creates yellow sprites as long as it is pressed down. The yellow sprite is just a yellow pixel that moves towards the center of the screen. It is an Area2D with a Sprite and a CollisionShape2D under it.

The Remote Inspector is very useful! I was able to get my code to kind-of work using the following:

func _ready():
	set_process(true)
	for n in get_tree().get_nodes_in_group("ship_group"):
		n.connect("area_enter",self,"_on_ship_body_enter")

Now it is able to connect to all of the existing ships in a ship group that I created. I still have a problem in that it isn’t connected to ships created after the yellow sprite. Any ideas?

Jambers | 2017-07-04 04:11

:bust_in_silhouette: Reply From: aozasori

I suggest you do something like the following instead, so you won’t have to worry about connecting every single ship instance to every single yellow_sprite instance.

In the script of yellow_sprite:

var target_group = "ship_group"

func _ready():
  connect("area_enter", self, "_on_area_enter")

func _on_area_enter(target):
	if target.is_in_group(target_group):
		target.do_this_when_hit()

And do this for ship:

  1. Add the node to the proper group (eg, ship_group).
  2. In the script, have any required functions defined (eg, do_this_when_hit).