How do I change the function of a button?

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

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?

:bust_in_silhouette: Reply From: timothybrentwood

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: