I want to remove an option from a dropdown by name but can’t seem to get this working.
I’ve tried:
Dropdownname.options.Remove(“itemname”);
I want to remove an option from a dropdown by name but can’t seem to get this working.
I’ve tried:
Dropdownname.options.Remove(“itemname”);
options is a list of OptionData, so if you want to remove by name, you need to loop through and check the text of the optionData to see if it matches what you want to remove, then use removeAt on the index. That would be one way of doing it.
https://docs.unity3d.com/ScriptReference/UI.Dropdown.OptionData.html
that sounds like at runtime it’ll tell me what index the item is at then I have to code it for the index, but thats not what I need it to do I need it to remove the item OnDisable();.
because if I remove the index everything in the list changes its index and that would require me to check every index for that text all over again.
do you know what the Remove() is for? because I thought it would be what I needed.
Options is a list. But it’s a list of OptionData, so if you wanted to use remove, you’d have to have a reference to the OptionData that you want to remove.
So if you had this
OptionData myOptionData = Dropdownname.options.find((x) => x.text == “someString”);
Dropdownname.options.Remove(myOptionData);
Honestly, just do a loop and check the options text. When you find the one that matches, remove it. Unless you have thousands and thousands of options, the loop is quick and should have no impact. You don’t need to know at runtime the index. You just loop through it, if the text matches the string, then you removeat the index.
for(int x = 0; x < Dropdownname.options.Count;x++)
{
if(Dropdownname.options[x].text == "someString")
{
Dropdownname.RemoveAt(x);
break;
}
}
Not tested, but should work.
The way you are using Remove would work if it was a list of strings, but it’s not.
Ok I get what the loop does but doesn’t the loop run once? I need it to check every Item in the dropdown if it matches any item I have in List and then remove all the matches from the Dropdown. So do I do something like this?
List Types = new List();
public Dropdown TypeList;
void OnDisable(){
foreach(string Type in Types){
for(int x = 0; x < TypeList.options.Count;x++)
{
if(TypeList.options[×].text == Type)
{
TypeList.options.RemoveAt(x);
break;
}
}
}
}
Then just loop backwards from the end of the list and don’t break when you find a match
for (int i = options.Count - 1; i >=0; i--)
{
if (options[i].text == Type) options.RemoveAt(i);
}
private void RemoveAllItemsInDropdown(TMP_Dropdown dropdownTMP)
{
if(dropdownTMP == null) return;
var totalItem = dropdownTMP.options.Count;
for (int i = totalItem - 1; i >=0; i--)
{
var textWrite = dropdownTMP.options[i].text;
if(!string.IsNullOrEmpty(textWrite))
{
dropdownTMP.options.RemoveAt(i);
}
}
}