First, I haven't tried any of this... :) My suggestions are only from a quick look at the docs.
- To select an item programmatically (which is what you ultimately need to do here I think...), you need it's INDEX (
select(index)
).
- You've said that the indices can change, so that's not a stable mechanism to track a given item by.
- You can specify a unique ID for each item when you add it (
add_item("my item", 23)
) for example.
- You can get an item's Index from its ID (
get_item_index(id)
)
So, if you assign a unique ID to each item, and store that ID in your DB, you can can map it to that item's INDEX in a given OptionButton
, and from there, you can select that item via code.
However, maybe there's an easier way for you to do this based on the item's TEXT value - which is apparently what you already have stored... Here's an example:
func _ready():
$OptionButton.add_item("Item 1")
$OptionButton.add_item("Item 2")
$OptionButton.add_item("Item 3")
$OptionButton.add_item("Item 4")
$OptionButton.add_item("Item 5")
$OptionButton.add_item("Item 6")
var item_to_select = "Item 3"
for i in $OptionButton.get_item_count():
var text = $OptionButton.get_item_text(i)
if text == item_to_select:
$OptionButton.select(i)
break
The above code just iterates through all items in a given OptionButton
looking for one with a specific text string. Once that's found, that item is selected via its index.