0 votes

`extends Panel

var butt1 = "Nope!"
var butt2 = "Wrong!"
var butt3 = "Not It!"
var butt4 = "Winner Winner Chicken Dinner!"

func ready():
for button in get
button.connect("pressed", self, "
onbuttonpressed", [button])

func somebutton_pressed(button):

func onButtonpressed():
node("Label").text = "Nope!"

func onButton2pressed():
node("Label").text = "Wrong!"

func onButton3pressed():
node("Label").text = "Not It!"

func onButton4pressed():
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 somebutton_pressed() function. I know I have to be missing something obvious but I am not seeing it. Thanks and sorry for the N00b question.

Godot version 3.0
in Engine by (12 points)

2 Answers

0 votes

The easiest way is to create a dictionary, you can also use a match statement or a series of if elifs:

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():
        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:

func do_something_cool():

func do_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.

by (3,707 points)
0 votes

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.

by (1,067 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.