Search code examples
c#stringunity-game-enginesearchdropdown

Unity Searchable Dropdown


Hello everyone I am trying to make a Searchable Dropdown with TMPro InputField. It currently gets the first letter but I couldn't figure out how to add the other letters. For example if I write "a" in input field it gets me the options that start with the letter "a" but if I wrote "an" nothing changes.

 private void Start()
    {
        UpdateEmoteDropdown();

    }

    public void UpdateEmoteDropdown()
    {

        CurrentText = InputField.text;

        emoteDropdown.options.Clear();

        emoteDropdown.value = 0;

        foreach (var animation in Enum.GetValues(typeof(Animations)))
        {
            string name = Enum.GetName(typeof(Animations), animation);

            if (CurrentText.Length == 0)
            {
                emoteDropdown.options.Add(new Dropdown.OptionData()
                {
                    text = name
                });

            }
            else {
                if (CurrentText[0] == name[0])
                {
                    emoteDropdown.options.Add(new Dropdown.OptionData()
                    {
                        text = name
                    });
                }
            }

        }

        emoteDropdown.RefreshShownValue();

        emoteDropdown.value = 0;
}


Solution

  • Well you only ever check the very first letter in

    if(CurrentText[0] == name[0])
    

    what about rather using e.g. string.StartsWith

    if(name.StartsWith(CurrentText))
    

    or if you even want to include results that contain the given string at any point not just the beginning rather use string.Contains

    if(name.Contains(CurrentText))