Search Unity

Question Sorting a TMP_Dropdown List<OptionData>

Discussion in 'UGUI & TextMesh Pro' started by chris_gamedev, Mar 12, 2021.

  1. chris_gamedev

    chris_gamedev

    Joined:
    Feb 10, 2018
    Posts:
    34
    Hello,

    I have a feeling I'm overcomplicating this, so I thought I should seek opinion.

    If we consider this code which grabs an array of things, loops through them and adds the string name of each one to the dropdown options.

    Code (CSharp):
    1.  
    2. var dropdown = GetComponent<TMP_Dropdown>();
    3. dropdown.options.Clear();
    4.  
    5. CustomThing[] customThings = GetCustomThings();
    6.  
    7. for (var i = 0; i < customThings.Length; i++)
    8. {
    9.     // do some stuff...
    10.  
    11.     dropdown.options.Add(new TMP_Dropdown.OptionData() { text = customThings[i].GetThingName() });
    12.  
    13.     // ... and some more stuff
    14. }
    15.  
    This all works beautifully.

    However, assume now that
    customThings
    is in a predetermined order, but that order isn't necessarily in alphabetical order by name.

    In other words, the dropdown may appear in this order:
    • Zebra
    • Cow
    • Elephant
    • Dog
    Instead of this order:
    • Cow
    • Dog
    • Elephant
    • Zebra
    If we assume that I can't easily change the order of my CustomThings array, it seems that my only option is to write my own Comparer to compare
    TMP_Dropdown.OptionData
    objects.

    Code (CSharp):
    1.  
    2. private class TMPCompare : IComparer<TMP_Dropdown.OptionData>
    3. {
    4.     public int Compare(TMP_Dropdown.OptionData x, TMP_Dropdown.OptionData y)
    5.     {
    6.         return new CaseInsensitiveComparer().Compare(x.text, y.text);
    7.     }
    8. }
    9.  
    10. ...
    11.  
    12. // add CustomThing[] items to dropdown
    13.  
    14. dropdown.options.Sort(new TMPCompare());
    15. dropdown.RefreshShownValue();
    16.  
    This is fine, I guess, but is there nothing built-in to TMP which would just sort this automatically?

    Side note: I appreciate I probably can sort my CustomThing array. Probably using a Comparer :p But maybe I'm missing something that would make this easier.

    Thanks for reading if you got this far!