I am trying to pass a value from a UI dropdown object (using OnValueChanged) into another script, so that the value selected controls what enum value is selected in the inspector for that other script. For example, I would like my UI selection to select “Item 2” of the enum in the target script (the code for which is below):
using UnityEngine;
public class UpgradeModule : MonoBehaviour
{
public MyEnum myDropDown = new MyEnum();
}
public enum MyEnum
{
Item1,
Item2,
Item3
};
How do I do this?
You can convert the dropDown value to an enum, it’s be something like this
using UnityEngine;
using UnityEngine.UI;
public class GetDropDownValue : MonoBehaviour
{
public Dropdown dropdown;
public enum DropDownSelection { A, B, C }
public DropDownSelection selection;
private void Awake()
{
dropdown.onValueChanged.AddListener(delegate { DropdownValueChanged(dropdown); });//Add listener to Event
}
void DropdownValueChanged(Dropdown change)
{
selection = (DropDownSelection)change.value; //Convert dropwdown value to enum
}
}
Edit:
For populate a dropdown with an enum, you will need to use the “System” namespace to get acess to the “Enum” type, see:
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DropDownPopulation : MonoBehaviour
{
public Dropdown dropdown;
[System.Serializable]
public enum FormatPresetType
{
RGB,
CMYK
}
FormatPresetType formatPreset;
private void Awake()
{
PopulateDropDownWithEnum(dropdown, formatPreset);
}
public static void PopulateDropDownWithEnum(Dropdown dropdown, Enum targetEnum)//You can populate any dropdown with any enum with this method
{
Type enumType = targetEnum.GetType();//Type of enum(FormatPresetType in my example)
List<Dropdown.OptionData> newOptions = new List<Dropdown.OptionData>();
for(int i = 0; i < Enum.GetNames(enumType).Length; i++)//Populate new Options
{
newOptions.Add(new Dropdown.OptionData(Enum.GetName(enumType, i)));
}
dropdown.ClearOptions();//Clear old options
dropdown.AddOptions(newOptions);//Add new options
}
}
Thank you! This seems to work if I want to create an enum list within this script, but in my other script I already have an enum list, and I want the dropdown on the UI object to be populated with these values, so that when I make a change in the UI, it selects from that list in the script. Maybe I’m thinking about it wrong, but here’s an example of what’s actually in the script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu("Color/ColorListener")]
[RequireComponent(typeof(AudioListener))]
[ExecuteInEditMode]
public class ColorListener : MonoBehaviour
{
[System.Serializable]
public enum FormatPresetType
{
RGB,
CMYK
}
[System.Serializable]
public enum PatternPresetType
{
Black,
White,
Red,
Orange,
Yellow,
Blue,
Custom
}
}