|
|
|
 |
Attention |
Topic was automatically imported from the old Question2Answer platform. |
 |
Asked By |
BoredGoddess |
`extends Panel
var butt1 = “Nope!”
var butt2 = “Wrong!”
var butt3 = “Not It!”
var butt4 = “Winner Winner Chicken Dinner!”
func _ready():
for button in get_tree().get_nodes_in_group(“Buttons”):
button.connect(“pressed”, self, “_on_button_pressed”, [button])
func _some_button_pressed(button):
func _on_Button_pressed():
get_node(“Label”).text = “Nope!”
func _on_Button2_pressed():
get_node(“Label”).text = “Wrong!”
func _on_Button3_pressed():
get_node(“Label”).text = “Not It!”
func _on_Button4_pressed():
get_node(“Label”).text = “Winner Winner Chicken Dinner!”`
So I have multiple buttons and want a different result depending on what button is pressed but I am having a heck of a time figuring out how to put that into my _some_button_pressed() function. I know I have to be missing something obvious but I am not seeing it. Thanks and sorry for the N00b question.
|
|
|
 |
Reply From: |
timothybrentwood |
The easiest way is to create a dictionary, you can also use a match
statement or a series of if
elif
s:
extends GridContainer
var button_functions : Dictionary
func _ready():
var button1 = Button.new()
var button2 = Button.new()
button_functions = {button1 : "do_something_cool",
button2 : "do_something"}
for button in button_functions.keys():
self.add_child(button)
button.text = button_functions.get(button)
button.connect("pressed", self, "some_button_pressed", [button])
func some_button_pressed(button):
var function_to_call = button_functions.get(button)
if function_to_call:
call(function_to_call)
func do_something_cool():
print("cool")
func do_something():
print("something")
Here I am using a dictionary
with the keys
being the buttons
pressed that maps those buttons
to which function
they should call.
Note that I switched the node type from a Panel
to a GridContainer
because it doesn’t make much sense to store buttons in a Panel
, they should be stored in some kind of a Container
node.
I am creating the buttons through code here but you can just as easily do:
onready var button1 = get_node("path/to/my/button1")
above the _ready()
function.
|
|
|
 |
Reply From: |
magicalogic |
You are connecting the signals well but declaring the receiving method wrongly.
Declare it as : on_button_pressed(button):
so that it can receive the pressed button.
To set different text depending on the pressed button, type:
if button.name == "button_name":
$"Label".text = "text for that button"
Then get rid of the other methods, you only need one.
Hopefully this helps.