How do get a parent to listen to multiple dynamically instanced children when the children don't exist at the start?

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

I’m adding more features to the “Your First Game”. Currently I’m trying to increase the score when a bullet collides with a creep.

My initial attempt was to emit a custom signal from within the Bullet scene and then connect that to a function inside the Main scene. Almost none of the signals are detected (it did seem to detect once in a while, is that a bug?), so I concluded that it’s because the bullets don’t exist initially.

I currently am exporting the Bullet PackedScene into the Player scene.

Do you need to set up a listener for each Bullet child instance (is that possible)? Or is there just a flaw in my structuring?

:bust_in_silhouette: Reply From: njamster

It probably would be easier to help you, if you provided any code.

That being said, if “the children don’t exist at the start”, I assume you instance them from code during runtime. That’s where you should connect the signal as well:

var BULLET_SCENE = preload("res://Bullet.tscn")

func spawn_bullet():
    var new_bullet = BULLET_SCENE.instance()

    new_bullet.connect("fired", self, "_on_fired")

    # you can provide an array of extra arguments to the callback 
    new_bullet.connect("hit", self, "_on_hit", [new_bullet])

    add_child(new_bullet)

func _on_fired():
    print("BANG BANG BANG")

func _on_hit(bullet):
    print("OUCH! Something was hit by ", bullet)