add a signal to new instaces

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

so, i have one label that i want to increment points by catch coins instances.
label is in the main scene and i cant connect the signal

i only have this, in the main

func timer_timeout()
var coin =preload("res://coin.tscn).instance()

i tryed

and in the label
func on_coin: print(“hi”)
but nothing

:bust_in_silhouette: Reply From: Bean_of_all_Beans

Okay, so here is what you are doing incorrectly from what I’ve seen:

You try to preload the coin scene in the function timer_time_out. To my knowledge, preload only works when done outside of a function, like declaring global or local variables for use in the script. For example, you put var coin = preload("res://coin.tscn") above your other functions in the script file. So, when you call timer_time_out, you just put var coin_instance = coin.instance() then add_child(coin_instance). Of course, you can call it whatever you would like.

Next, connect connects signals based on who is calling it. self.connect("coin", coin, "on_coin") is saying the script itself will try and connect the signal coin to the instanced coin scene’s function “on_coin”. However, if your script does not define the signal coin, this will not work. Realistically, you would want to call coin_instance.connect("coin", self, "on_coin"). This would tell the coin instance to connect its coin signal to the current script’s function (the current script is the self in this connect call) on_coin.

Now, to have the Label’s on_coin function called, you might need to write this in the main script:

coin_instance.connect("coin", $Label, "on_coin")

This, of course, depends on what you called your Label, so replace “Label” with the name you gave it, if you changed the name.

To reiterate the above:

You call the coin_instance’s connect function, passing it the name of the signal (“coin”); the target who will receive this signal, $Label in this case; and the name of the function it will call, “on_coin”.