This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

I've been trying to figure out a way to alter the function that's connected to a button in GDScript using the .connect() function, but it doesn't seem to work.

It gives me errors:
connect: Signal 'pressed' is already connected to given method 'function' in that object.

I'm wondering if there's any way to override the previous function with a new function, as I'm looking to use the same buttons but have them do different functions based on the situation.

Alternatively, is there another way to set and change the function that's meant to be connected to the button?

Godot version v3.4.stable.official [206ba70f4]
in Engine by (12 points)

1 Answer

0 votes

Here is a way to swap the function a button is connected to without errors:

onready var button = get_node("Button")

func _ready():
    button.connect("button_up", self, "a")

func _input(event: InputEvent) -> void:
    if event.is_action_released("ui_accept"):

func change_button_function(b : Button):
    if b.is_connected("button_up", self, "a"):
        b.disconnect("button_up", self, "a")
        b.connect("button_up", self, "b")
        b.disconnect("button_up", self, "b")
        b.connect("button_up", self, "a")

func a():

func b():

In order to not get the "Signal XXX is already connected to given method" error that you were getting, check if the button is already connected to that signal using the is_connected() method before connecting the signal. The get_signal_connection_list() function may be useful for you as well. You might find looking over the Object class API helpful as well:

by (3,906 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 Frequently asked questions and 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 [email protected] with your username.