Posts
Search
Contact
Cookies
About
RSS

Godot - auto populate OptionButton from Enum

Added 9 Mar 2025, 2:26 p.m. edited 9 Mar 2025, 2:49 p.m.

Its an important principle in coding that you never maintain two sources of the same truth...

Lets say we have an enum inside an Entity class

enum Type {
INVALID = 0,
IMP = 2,
ORC = 4,
SKELETON = 6,
SLIME = 8,
WARRIOR = 10,
MAGE = 12,
ARCHER = 14
}

(note that the values don't align with the index of the keys...)

While you could maintain the option buttons list manually this would be a pain and also be very likely to break when for example you modify the enum and forget to update the option button.

Instead lets use the "name" of the ENUM item in the button and its value as the ID (for the option button list ID)

In your user interface scene use this code

func _ready() -> void:
for en in Entity.Type.keys():
option_button.add_item(en, Entity.Type[en])

By way of proving this does actually work, you can use an on change signal function

func _on_option_button_item_selected(index: int) -> void:
# id is the enum value == Entity.Type.XXX
var id = option_button.get_item_id(index)
# print out its "name"
print(Entity.Type.find_key(id))
The ID you get from the OptionButton is the enum's value, as can be seen by printing out its key...

While this looks obvious and simple, I don't mind admitting it took a little while to get right ! Its all too easy to get it nearly right or just land you scratching your head...

Enjoy!