How to connect a signal from an instanced node

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

I’m instancing a button in my scene and I want to be able to connect the _pressed() signal to the main scene it’s being instanced in. How can I do this without a singleton?

I could have the button emit a signal in the _ready function and then connect it in the main script, but I have no way to access the button without making it a singleton. Is there a way to access it only after the button is instanced?

:bust_in_silhouette: Reply From: adabru

Sure you can’t connect it via

$MyButton.connect("pressed", self, "my_function")

like explained on this page?

No, MyButton is not a child (until it’s instanced) so using $MyButton wouldn’t work

I did solve it however by using:

MyButton = button.instance

this works the same way as $MyButton, at least how I’ve been using it

DigitalDrako | 2020-06-12 18:34

Nice you solved it!
So you managed to get a reference to the button node.

adabru | 2020-06-13 06:06

Quick question how exactly did you use this? did you just replace the $MyButton with button.instance or is that a line of code you added before the .conect? as i think i am trying to do something similar with instanced pickups form mob drops.

ForgottenStar | 2021-07-04 21:07

You should be able to do sth. like:

myButton = button.instance()
addChild(myButton)
myButton.connect("pressed", self, "my_function")

adabru | 2021-07-12 20:08

:bust_in_silhouette: Reply From: kuzey

in Godot 4, you can try this:

var bullet = bulletScene.instantiate()
bullet.connect('hit', _on_player_hit)

And your callable function:

func _on_player_hit():
  print('Hit!')