How to press a button from code?

Godot Version

4.2.1.stable

Question

Is there a way to press a button from GDScript code? My best idea is to both call the method “_pressed” and send the signal “pressed”, but I’m not sure that will do everything the button does when it’s pressed. I just want a virtual finger to press the button possibly in the argument of a call_deferred method, so it will be pressed when the game is properly running, like a very fast player would click on the button right after the game starts.

Not sure if there’s a better way but you can create a mouse input to click the button, (I haven’t tested if it actually works with buttons…):

func left_click(pos):
	var press = InputEventMouseButton.new()
	press.set_button_index(MOUSE_BUTTON_LEFT)
	press.set_position(pos)
	press.set_pressed(true)
	Input.parse_input_event(press)
	var release = InputEventMouseButton.new()
	release.set_button_index(MOUSE_BUTTON_LEFT)
	release.set_position(pos)
	release.set_pressed(false)
	Input.parse_input_event(release)
1 Like

You could put the code when the button is pressed into a function and call the function when it is pressed. Then you could call the same function wherever and whenever you want in the code.

Thank you all for the suggestions. I guess, the mouse input is the closest to what I asked for. Turns out in my case calling the _pressed method and emitting a pressed signal works in my case, but I’m not sure it’s universal.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.