Buttons instanced through script are disabled

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

I might be overlooking something, but when i instance a scene containing a button, that button doesnt register clicks. On its own the button scene works and i can emit signals from its _ready function, but once i instance it from code neither the signal, nor the simple buttonclick callback doesnt run, and the button doesnt take the “pressed” texture.


Button scene setup:
→ Node2d
… → Button

Button scene script:

extends Node2D
signal _animal_button_pressed(name)
func _on_Button_pressed():
    emit_signal("_animal_button_pressed", animal_name)

Game script:

var button = load("res://Scenes/AnimalButton.tscn").instance()
button.connect("_animal_button_pressed", self, "_on_animal_button_pressed")
...
func _on_animal_button_pressed(name):
    print(name)

Seems like adding a child to a Node2D or a Control, so that

->Node2D | Control
…->Node2D
…->Button

Doesnt work? Added the buttons to the scene root and they work perfectly but i have no idea why.

RazorSh4rk | 2020-05-21 00:25

:bust_in_silhouette: Reply From: astrale-sharp

Okay here is whats happening:
The method on_button_pressed is not automatically connected to the pressed signal of the button. So a quick fix could be adding this snippet of code to the ready function of the button:
connect (“pressed”, self,“on_button_pressed”) #which would connect the signal to your function
But its a little weird, theres lot of unnecessary signals

So here how i think its best fixed:
In your game script you instance the button and then you directly connect it to on_animalbuttonpressed

Im on my phone so i can’t write good code that you can copy as is, sorry about that
Dont hesitate to ask for clarification!
Good luck: )

Im not really instancing a button, it has a parent, so i cant just connect onbuttonpressed to the instanced scene, and i connected the button to its script in the editor, that works fine.

RazorSh4rk | 2020-05-21 10:53