How do I add singals to instantiated/created buttons in GDScript?
Asked Answered
S

3

0

Hello, I've written some GDScript that creates some buttons with their own icons, text and etc in a for loop.
However, my issue is having them have their own signals that do different actions, I've tried multiple methods
and have reviewed the documentation for signals and buttons but still couldn't come up with a solution.

Sphygmograph answered 10/7, 2023 at 6:49 Comment(0)
A
0

have their own signals

If you want custom signals you have to extend the button class, add a signal and emit it somewhere.

extends button

signal my_signal

func  _ready():
	emit_signal("my_signal", "my_argument")

https://docs.godotengine.org/en/stable/classes/class_object.html#class-object-method-emit-signal

Anywheres answered 10/7, 2023 at 7:27 Comment(0)
A
0
  • I think your problem is that all buttons do the same thing right?
  • So here is an ugly solution for this, I hope someone has a better one.
  • You need to make a new button class that extends Button
  • Here:
class_name MessageButton extends Button

@export var message: String = "" # This holds the message each button communicates with.

# button_pressed is a bool and pressed is a signal of Button :/
signal message_button_pressed(message: String)

func _ready():
  #connect the pressed signal to a function
  pressed.connect(_on_button_pressed) # Godot 4.x

func _on_button_pressed():
  # when button is pressed, emit a signal with a message of what the button wants
  message_button_pressed.emit(message) # also godot 4.x
  • Now inside your for loop, make sure that you are now dealing with MessageButton type and not just Button. And that the buttons you instantiate are MessageButton.
  • Inside your for loop, in addition to giving each button its unique text and icon, now you give it its own message.
  • connect each button's signal to a function
    some_message_button.message_button_pressed.connect(_on_message_button_pressed)
  • Inside the function use match statement
    func _on_message_button_pressed(message: String):
      match message:
        "message1":
          # Do some stuff
          pass
        "message2":
          # Other stuff
          pass
        "quit":
          get_tree().quit()
    Edit: formatting, typos
Alternative answered 10/7, 2023 at 7:44 Comment(0)
A
0

that's one way ... maybe you want to show us your script where you create your buttons.

There are many ways to archive this ... you could also use lambda functions or connect them to a overlaying script that has all the functions in it.

Anywheres answered 10/7, 2023 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.