Button Array logic that helps work itself

Godot Version

4.6.1

Question

I’m trying to make some logic apply to all button nodes in an array without having to type out each node each time for one big of logic. The code below works for what I want it to do, but I don’t want it to be new logic each time I put a new button in the scene for what is essentially doing the same thing each time. What i’ve been trying to do is for it to take whatever button I am currently hovering over, tell me that node’s index on the array, and make the new index that button’s index, as well as releasing that button’s focus. I’ve been bashing my head against a wall for like a day now and can’t figure it out though. Any help is appreciated, even just telling me my method sucks.

if NGButton.is_hovered() && last_mouse_pos != current_mouse_pos:
	index = 0
	NGButton.release_focus()
if CNTButton.is_hovered() && last_mouse_pos != current_mouse_pos:
	index = 1
	CNTButton.release_focus()

I’m not sure exactly what you need but..

You can use a ButtonGroup for all of the buttons you need. It may be easier to handle them, rather than the array.

And for the ‘logic’ part, you can use a main node attached with a script, that also has the reference of ButtonGroup. You can connect signals of each button to the same function in your script and do the logic there.

Make your own button:

class_name MyOwnButton
extends Button

var last_mouse_pos: Vector2

func _ready():
....etc.

Add the mouse position tracking and focusing code there. Then convert all your regular Buttons to these MyOwnButtons.

1 Like