Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting drop down value in unity with a string

Tags:

c#

unity3d

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";
like image 384
Hikari Avatar asked Jan 03 '19 10:01

Hikari


3 Answers

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");
like image 138
derHugo Avatar answered Oct 23 '22 15:10

derHugo


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");
like image 38
Codemaker Avatar answered Oct 23 '22 13:10

Codemaker


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

like image 1
Remy Avatar answered Oct 23 '22 15:10

Remy