- Home /
How to use the new Dropdown Menu?
Im very familiar with the unity 5 UI, especially with buttons, the way buttons work are calling a method... But I don't seem to find nor have any idea how to call a Method when clicking a certain option in the dropdown.
I have my own method called UseItem() and needs to be used when the first option in the dropdown is clicked. How can I achieve this? An example code or a reference would be great! Thanks, in advance :D
Answer by Kwarts · Oct 06, 2015 at 08:41 AM
Here's a quick example in C#
using UnityEngine;
using UnityEngine.UI;
public Dropdown myDropdown;
void Start() {
myDropdown.onValueChanged.AddListener(delegate {
myDropdownValueChangedHandler(myDropdown);
});
}
void Destroy() {
myDropdown.onValueChanged.RemoveAllListeners();
}
private void myDropdownValueChangedHandler(Dropdown target) {
Debug.Log("selected: "+target.value);
}
public void SetDropdownIndex(int index) {
myDropdown.value = index;
}
This helped way more than the Unity documentation. I found all that was really needed is the 'myDropdownValueChangedHandler' that receives UnityEngine.UI.Dropdown. The rest is easily wired up in the editor :
$$anonymous$$ake a gameObject that uses the above script. Lets call it 'DropDownTarget'
add OnValueChanged event to the drop down
drag the 'DropDownTarget' to the event to receive the event notification
In the function drop down, select DropDownTarget->myDropdownValueChangedHandler
Drag your drop down object to the function arg.
But doesn't myDropDownValueChangedHandler need to public, not private? Otherwise it won't show up in the function dropdown on the OnValueChanged property drawer.
how does this work when your myDropdown object is not initialized? thanks!
Please, open a new question showing more info about your own problem. Unity Answers it NOT the Forums, and should not be used like that.
Wait, do I need to add a listener to even get it to drop down? I wasn't having a problem reading the resultant value, it just didn't function at all.
Answer by DiegoSLTS · Sep 13, 2015 at 06:59 PM
Look here: http://docs.unity3d.com/Manual/script-Dropdown.html
You have to set a callback for the "OnValueChanged" event. That function will get an int as a parameter, which is the index of the selected item in the Dropdown.
Is there a tutorial somewhere for this? I'm also trying to figure this out.
I haven't looked for tutorials but if you post a question here on Unity Answers or in the forum with your desired effect or description of the information you need, people will surely get you started.
Wait, do I need to add a listener to even get it to drop down? I wasn't having a problem reading the resultant value, it just didn't function at all.