Connecting signals on instanced scenes/child scenes in GDScript

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

So I am building a carnival style whack-a-mole (i know, crazy complicated, but starting simple has helped me learn a lot of the fundamentals) and I have an enemy object listening to the player object (and signaling to the points collection object) for registering hits. Whenever i save the enemy scene and instance it, my signals i connected in the editor no longer function (despite all of this enemy object using the same script).

I am trying to wrap my head around how to connect these instanced nodes within their code as I am sure that is the solution, likely a line in func _ready() or func _on_Scene_tree_entered(). I have read the docs and tried to implement the code and I can’t seem to get this important idea down. I understand (hopefully, do correct me if i’m wrong!) that moving up a SceneTree Godot is a tougher task than moving down the tree?

So in short: how do you implement connecting signals within code, to objects AND from objects, when you are instancing a PackedScene?

:bust_in_silhouette: Reply From: Inces

You propably connected only one particular mole from the starting scene to the listener.

It is better to disconnect it there, and code it in mole script :

onready var listener = #reference to your listener here 
func ready():
        connect( "whack", listener, "on_whack")

first argument is signal name, 2nd is node to listen, 3rd is a name of function in listener that will trigger. You can also add 4th argument and more, they will be passed as additional information. For example You can pass reference to a mole being hit by entering self as 4th argument. The same can be done when emitting signal :
emit_signal(“whack”, self)

Thank you for enlightening me. Sometimes I need a bit more info than the docs and visual examples help outside of full game tutorials. Many thanks! I will give this a go.

SnapCracklins | 2022-03-21 17:04

:bust_in_silhouette: Reply From: JCNegar

You can connect the signals through code in the script of the parent of your elements.
For example this is your tree after instancing:
|_ Enemy
|_ Player

As the World node is a mutual parent for both of the Enemy and player scene, It’ll be easy to locate them, If you attach a script to the world node, Connecting signals should be much easier. This article can help you too, Make sure you take a look at it

That was insightful. It also helped me to isolate another problem with how my trees are built and how i test/code instancing. Thanks for that. Nitty gritty details like this are usually my weakness.

SnapCracklins | 2022-03-21 17:05