Disable/Enable item in OptionButton

Godot Version

4.3

Question

Hi, I’m making a sort of “draft” type program where you can choose an option from multiple option buttons that are filled with names. A player can choose an option on one slot but should be disabled from another slot. I got that part like this:

func _on_item_selected(index: int) -> void:
	#disables current selected index for all buttons
	for node in get_tree().get_nodes_in_group("buttons"):
		node.set_item_disabled(index,true)

And that works fine, but the player can change their mind and switch them to another slot.
So I added …

func _on_item_selected(index: int) -> void:
	#disables current selected index for all buttons
	for node in get_tree().get_nodes_in_group("buttons"):
		node.set_item_disabled(index,true)

		for item in node.get_item_count():
			if node.get_item_index(item) != index:
				node.set_item_disabled(item, false) 

Say I have 3 buttons in a “buttons” group, with identical index lists. I select option 1 from button 1 so it disables option 1 from all other buttons so button 2 and 3 can not select it.
Then button 2 chooses item 2, but this code re-enables option 1 from button 1 for all buttons while disabling option 2 from button 1 and 3.

So I want to re-enable a choice that was CLICKED AWAY from from all other option buttons but NOT re-enable an item from a button with an item already selected.
I think I have to use get_selected() somewhere but I’m not sure where and how.

I think you’d need to cache the previously selected index as a member variable on each option button and re-enable it on the other buttons upon selection changes.

var previously_selected: int = -1

func _on_item_selected(index: int) -> void:
	#disables current selected index for all buttons
	for node in get_tree().get_nodes_in_group("buttons"):
		node.set_item_disabled(index,true)
		node.set_item_disabled(previously_selected,false)

	previously_selected = index

I haven’t tested this code. You might need to implement some guard clauses here to make this code more secure, but the principle should work.

1 Like

That worked perfectly, thank you so much I was overthinking it so much I started nesting loops :sob:

1 Like