Connecting a signal from a instantiated node

Godot Version

Godot 4.4.1-stable.official [49a5bc7b6]

Question

Hello everyone,

Keeping on learning code throught GDscript and Godot (begginer here), I am stuck with connecting signal coming from instantiated nodes.

Basically, what (part of) my game is :
-a level with its own code
-a player (characterbody2D)
-ennemies (Area2D) which are instantiated in the level. Several of this node can exist at the same time.

The ennemies emit a custom signal when they touch the player.

extends Area2D
signal touch
func _on_body_entered(body: Node2D) -> void:
	if body.name == "Player" :
		touch.emit()

I want the level to receive the emited signal. Problem is, the path of the ennemy node changes with the instances.

the best way I could come with is to connect the signal is (in level scene) :slight_smile:

$"./Ennemy".connect("touch", nextaction)

The problem being that it will only work with the first ennemy which is instantiated, since the other ones will have a different path.

I was wondering if it was possible to have a dynamic way of calling the path of the instantiated node in order to solve this issue ? Or maybe another solution ?

Thank you very much !

Where do you instance the enemies?

If you instance them in the level script you already have the reference to the new instance and can connect it right there:

# level script

func instance_enemy():
    var enemy = enemy_scene.instantiate()
    enemy.connect("touch", nextaction)
    add_child(enemy)
2 Likes

Hi,

You can connect a signal right after you instantiate a node. Its name won’t be “Enemy”. You could also try calling the function directly from the enemy, but using signals is probably better. Also, when you write a piece of code, put it under ``` for multi-line code, and under ` for inline code, like so:
```
extends Area2D
signal touch
func _on_body_entered(body: Node2D) → void:
if body.name == “Player” :
touch.emit()
```
That way it will be formatted correctly:

extends Area2D
signal touch
func _on_body_entered(body: Node2D) → void:
	if body.name == “Player” :
		touch.emit()
1 Like

Thank you very much :smiley:

Your solution worked perfectly Tomyy. After spending a couple of hours to find it my on way… :smiley:
Thanks for the tip SecretAgent !

1 Like