Does anyone know how to set the dropdownUI value with a string in unity?
I know how to set it up with an int like these
public DropDown dropdown;
dropdown.value = 1;
However, what I want is to set the value with a given string.
Something like:
dropdown.value = "an Option";
Look at the documentation of Dropdown.value:
public int value;
The Value is the index number of the current selection in the Dropdown. 0 is the first option in the Dropdown, 1 is the second, and so on.
it is of type int
so in short: you can't
You could however get the index from the available options itself using IndexOf
:
// returns a list of the text properties of the options
var listAvailableStrings = dropdown.options.Select(option => option.text).ToList();
// returns the index of the given string
dropdown.value = listAvailableStrings.IndexOf("an Option");
you could do the same also in one line using FindIndex
dropdown.value = dropdown.options.FindIndex(option => option.text == "an Option");
We can't add string value to the dropdown value field. So if you need to show an option having the given string then use FindIndex option to find that option in the dropdown and then assign that index to the value field.
dropdown.value = dropdown.options.FindIndex(option => option.text == "an Option");
This answer was written under the assumption you wanted to set the text of a dropdown item. As setting the value as a string
is impossible, since the value is of type int
. See derHugo's answer for how you can get the index from an option.
dropdown.value
does not actually represent the text is shows. instead value
is the index number of the current selection in the Dropdown. 0 is the first option in the Dropdown, 1 is the second, and so on.
As described in the docs here
What you are looking for is Dropdown.itemText
(docs)
Meaning to set the text in your dropdown item you'll have to do the following: dropdown.itemText = "an Option";
A more complete guide on how dropdown menu's work can be found in the Unity manual here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With