简体   繁体   中英

C# Unity - How do you store a public int or float value in a dropdown so that the selected option returns a value?

I'm a bit of a beginner (to maybe an intermediate) and I was hoping to get some help on something I'm stuck on. Below is my code. I use C# and use Unity as the platform to create my projects.

What I'm trying to do is to manipulate "things" in real-time by clicking and selecting from options via the Dropdown UI in Unity. For example, let's say I have this game object that is moving left and right on the screen and let's say it's moving at a certain speed. These "things" that I want to manipulate can be like the "speed" of how fast this game object is moving. Thus, the game object that is moving left and right will still remain in that trajectory but the speed will update in real time based on what I select on the drop down IN REAL TIME. So I want to be able to select the set of options as many times as I want and the game object's speed keeps changing based on what I select.

There are other "things" I want to manipulate but that's the gist of what I'm trying to do.

Originally, I was hoping that selecting an option from the dropdown would return a value (preferably a float value because I only managed give an option an int value), and then I would store this float value into a public variable that I can call from another script. This way, I can update the "speed" for example of my game object with this new value.

I stumbled on a forum that gave this idea of using a dictionary to store both string and int as its keys. The problem is that this method has me create a public "void" methods for these variables that I store these values so I cannot call them.

I'm not sure if there is a better way to do all of this. It also doesn't have to be strictly a dropdown either but I do want some kind of interface in real-game-time that the user can adjust however they want that manipulates these "things" like "speed". I figured maybe a dropdown makes the most sense.

Thanks for any help!

public class DropdownHandler : MonoBehaviour
{
    //Dropdowns (Note: Drag the dropdown object into this reference in the inspector):
    [Header("Dropdown List")]
    public TMP_Dropdown dropdownAverageCharactersPerWord;
    public TMP_Dropdown dropdownWordsPerMinuteRates;
    public TMP_Dropdown dropdownFontSize;
    public TMP_Dropdown dropdownScreenWidthSize;


    //Dictionaries:
    public Dictionary<string, int> AverageCharactersPerWordDatabase = new Dictionary<string, int>()
    {
        { "Five", 5 },
        { "Six", 6 },
        { "Seven", 7 }
    };

    public Dictionary<string, int> WordsPerMinuteRatesDatabase = new Dictionary<string, int>()
    {
        { "85 Words Per Minute", 85 },
        { "105 Words Per Minute", 105 },
        { "143 Words Per Minute", 143 },
        { "173 Words Per Minute", 173 },
        { "205 Words Per Minute", 205 },
        { "240 Words Per Minute", 240 },
        { "275 Words Per Minute", 275 }
    };

    public Dictionary<string, int> FontSizeDatabase = new Dictionary<string, int>()
    {
        { "24", 24 }
    };

    private readonly Dictionary<string, int> ScreenWidthSizeDatabase = new Dictionary<string, int>()
    {
        { "1920", 1920 }
    };


    //Setting up all of the dropdowns via code:
    private void Awake()
    {
        if (dropdownAverageCharactersPerWord != null)
        {
            dropdownAverageCharactersPerWord.ClearOptions();
            dropdownAverageCharactersPerWord.AddOptions(AverageCharactersPerWordDatabase.Keys.ToList());
            dropdownAverageCharactersPerWord.onValueChanged.AddListener(DropdownValueChangedForAverageCharactersPerWord);
        }

        if (dropdownWordsPerMinuteRates != null)
        {
            dropdownWordsPerMinuteRates.ClearOptions();
            dropdownWordsPerMinuteRates.AddOptions(WordsPerMinuteRatesDatabase.Keys.ToList());
            dropdownWordsPerMinuteRates.onValueChanged.AddListener(DropdownValueChangedForWordsPerMinuteRates);
        }

        if (dropdownFontSize != null)
        {
            dropdownFontSize.ClearOptions();
            dropdownFontSize.AddOptions(FontSizeDatabase.Keys.ToList());
            dropdownFontSize.onValueChanged.AddListener(DropdownValueChangedForFontSize);
        }

        if (dropdownScreenWidthSize != null)
        {
            dropdownScreenWidthSize.ClearOptions();
            dropdownScreenWidthSize.AddOptions(ScreenWidthSizeDatabase.Keys.ToList());
            dropdownScreenWidthSize.onValueChanged.AddListener(DropdownValueChangedForScreenWidthSize);
        }
    }

    public void DropdownValueChangedForAverageCharactersPerWord (int newDropDownIndexPosition)
    {
        int averageCharactersPerWordDynamicVariable = AverageCharactersPerWordDatabase.Values.ElementAt(newDropDownIndexPosition);
        // averageCharactersPerWordDynamicVariable is the integer value associated with this key index

        //To Debug:
        Debug.Log("The selected Average Characters Per Word is " + averageCharactersPerWordDynamicVariable);
    }

    public void DropdownValueChangedForWordsPerMinuteRates (int newDropDownIndexPosition)
    {
        int wordsPerMinuteRatesDynamicVariable = WordsPerMinuteRatesDatabase.Values.ElementAt(newDropDownIndexPosition);
        // wordsPerMinuteRatesDynamicVariable is the integer value associated with this key index

        //To Debug:
        Debug.Log("The selected Words Per Minute Rates is " + wordsPerMinuteRatesDynamicVariable);
    }

    public void DropdownValueChangedForFontSize (int newDropDownIndexPosition)
    {
        int fontSizeDynamicVariable = FontSizeDatabase.Values.ElementAt(newDropDownIndexPosition);
        // fontSizeDynamicVariable is the integer value associated with this key index


        //To Debug:
        Debug.Log("The selected Font Size is " + fontSizeDynamicVariable);
    }

    public void DropdownValueChangedForScreenWidthSize (int newDropDownIndexPosition)
    {
        int screenWidthSizeDynamicVariable = ScreenWidthSizeDatabase.Values.ElementAt(newDropDownIndexPosition);
        // screenWidthSizeDynamicVariable is the integer value associated with this key index

        //To Debug:
        Debug.Log("The selected Screen Width Size is " + screenWidthSizeDynamicVariable);
    }
}

I think you can also consider using slider to adjust the speed value, as it gives you better control over a float value. Code sample as below:

public Slider slider;

void Start()
{
    slider.onValueChanged.AddListener(OnSliderValueChanged);
}

void OnSliderValueChanged(float value)
{
    // Do whatever you need with this value
}
  • Since you add your callbacks via code your methods can all be private (encapsulation).
  • Simply create convert the local int variables` in your methods into class fields
  • Actually instead of fields I would directly use Properties that others can access but only this class can assign

Something like eg

public class DropdownHandler : MonoBehaviour
{
    //Dropdowns (Note: Drag the dropdown object into this reference in the inspector):
    [Header("Dropdown List")]
    public TMP_Dropdown dropdownAverageCharactersPerWord;
    public TMP_Dropdown dropdownWordsPerMinuteRates;
    public TMP_Dropdown dropdownFontSize;
    public TMP_Dropdown dropdownScreenWidthSize;


    //Dictionaries:
    public Dictionary<string, int> AverageCharactersPerWordDatabase = new Dictionary<string, int>()
    {
        { "Five", 5 },
        { "Six", 6 },
        { "Seven", 7 }
    };

    public Dictionary<string, int> WordsPerMinuteRatesDatabase = new Dictionary<string, int>()
    {
        { "85 Words Per Minute", 85 },
        { "105 Words Per Minute", 105 },
        { "143 Words Per Minute", 143 },
        { "173 Words Per Minute", 173 },
        { "205 Words Per Minute", 205 },
        { "240 Words Per Minute", 240 },
        { "275 Words Per Minute", 275 }
    };

    public Dictionary<string, int> FontSizeDatabase = new Dictionary<string, int>()
    {
        { "24", 24 }
    };

    private readonly Dictionary<string, int> ScreenWidthSizeDatabase = new Dictionary<string, int>()
    {
        { "1920", 1920 }
    };

    // These are properties other classes can read but only this class may write 
    public int averageCharactersPerWordDynamicVariable {get; private set;};
    public int wordsPerMinuteRatesDynamicVariable{get; private set;}
    public int fontSizeDynamicVariable{get; private set;}

    // I make this one different.
    // This way it basically behaves the same way but you can see and edit
    // the value via the Inspector for easier debugging
    // up to you which way you want to go for
    [Header("Debugging")]
    [SerializeField] private int _screenWidthSizeDynamicVariable;
    public int screenWidthSizeDynamicVariable => _screenWidthSizeDynamicVariable;


    //Setting up all of the dropdowns via code:
    private void Awake()
    {
        if (dropdownAverageCharactersPerWord != null)
        {
            dropdownAverageCharactersPerWord.ClearOptions();
            dropdownAverageCharactersPerWord.AddOptions(AverageCharactersPerWordDatabase.Keys.ToList());
            dropdownAverageCharactersPerWord.onValueChanged.AddListener(DropdownValueChangedForAverageCharactersPerWord);
        }

        if (dropdownWordsPerMinuteRates != null)
        {
            dropdownWordsPerMinuteRates.ClearOptions();
            dropdownWordsPerMinuteRates.AddOptions(WordsPerMinuteRatesDatabase.Keys.ToList());
            dropdownWordsPerMinuteRates.onValueChanged.AddListener(DropdownValueChangedForWordsPerMinuteRates);
        }

        if (dropdownFontSize != null)
        {
            dropdownFontSize.ClearOptions();
            dropdownFontSize.AddOptions(FontSizeDatabase.Keys.ToList());
            dropdownFontSize.onValueChanged.AddListener(DropdownValueChangedForFontSize);
        }

        if (dropdownScreenWidthSize != null)
        {
            dropdownScreenWidthSize.ClearOptions();
            dropdownScreenWidthSize.AddOptions(ScreenWidthSizeDatabase.Keys.ToList());
            dropdownScreenWidthSize.onValueChanged.AddListener(DropdownValueChangedForScreenWidthSize);
        }
    }

    private void DropdownValueChangedForAverageCharactersPerWord (int newDropDownIndexPosition)
    {
        averageCharactersPerWordDynamicVariable = AverageCharactersPerWordDatabase.Values.ElementAt(newDropDownIndexPosition);
        // averageCharactersPerWordDynamicVariable is the integer value associated with this key index

        //To Debug:
        Debug.Log("The selected Average Characters Per Word is " + averageCharactersPerWordDynamicVariable);
    }

    private void DropdownValueChangedForWordsPerMinuteRates (int newDropDownIndexPosition)
    {
        wordsPerMinuteRatesDynamicVariable = WordsPerMinuteRatesDatabase.Values.ElementAt(newDropDownIndexPosition);
        // wordsPerMinuteRatesDynamicVariable is the integer value associated with this key index

        //To Debug:
        Debug.Log("The selected Words Per Minute Rates is " + wordsPerMinuteRatesDynamicVariable);
    }

    private void DropdownValueChangedForFontSize (int newDropDownIndexPosition)
    {
        fontSizeDynamicVariable = FontSizeDatabase.Values.ElementAt(newDropDownIndexPosition);
        // fontSizeDynamicVariable is the integer value associated with this key index


        //To Debug:
        Debug.Log("The selected Font Size is " + fontSizeDynamicVariable);
    }

    private void DropdownValueChangedForScreenWidthSize (int newDropDownIndexPosition)
    {
        _screenWidthSizeDynamicVariable = ScreenWidthSizeDatabase.Values.ElementAt(newDropDownIndexPosition);
        // screenWidthSizeDynamicVariable is the integer value associated with this key index

        //To Debug:
        Debug.Log("The selected Screen Width Size is " + screenWidthSizeDynamicVariable);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM