- Home /
Question by
SlevinKGames · Jun 22, 2020 at 10:00 PM ·
c#beginnerclassfilter
Better way to filter this function
Hi guys :) Basically i have written this part of code and I think there must be a cleaner way to write this. Unfortunately i have found no working solution that is working fine there. Maybe anyone of you got any pointers what I could do there?
public void FilterInventory(string filter)
{
if (filter == "Weapon")
{
MainInventarFilterText.text = "WEAPONS";
for (int i = 0; i < items.Count; i++)
{
if (uIItems[i].item is Weapon)
{
uIItems[i].transform.parent.gameObject.SetActive(true);
}
else
{
uIItems[i].transform.parent.gameObject.SetActive(false);
}
}
}
if (filter == "Clothing")
{
MainInventarFilterText.text = "CLOTHINGS";
for (int i = 0; i < items.Count; i++)
{
if (uIItems[i].item is Clothing)
{
uIItems[i].transform.parent.gameObject.SetActive(true);
}
else
{
uIItems[i].transform.parent.gameObject.SetActive(false);
}
}
}
if (filter == "Relic")
{
MainInventarFilterText.text = "RELICS";
for (int i = 0; i < items.Count; i++)
{
if (uIItems[i].item is Relic)
{
uIItems[i].transform.parent.gameObject.SetActive(true);
}
else
{
uIItems[i].transform.parent.gameObject.SetActive(false);
}
}
}
Thanks!
Comment
Best Answer
Answer by Hellium · Jun 22, 2020 at 10:40 PM
Code NOT TESTED, written from phone.
private Dictionary<Type, string> filters = new Dictionary<Type, string>()
{
{ typeof(Weapon), "WEAPONS" },
{ typeof(Clothing), "CLOTHINGS" },
{ typeof(Relic), "RELICS" }
};
public void FilterInventory(string filter)
{
foreach( var kvp in filters )
{
if (filter == kvp.Key.Name)
{
MainInventarFilterText.text = kvp.Value;
for (int i = 0; i < items.Count; i++)
uiItems[i].transform.parent.gameObject.SetActive(uiItems[I].GetType() == kvp.Key) ;
}
}
Answer by SofiaFeist · Jun 22, 2020 at 10:54 PM
Is this what you're looking for?
public void FilterInventory(string filter)
{
switch (filter)
{
case "Weapon":
FilterItem("WEAPONS", typeof(Weapon));
break;
case "Clothing":
FilterItem("CLOTHINGS", typeof(Clothing));
break;
case "Relic":
FilterItem("RELICS", typeof(Relic));
break;
}
}
private void FilterItem(string filterText, Type type)
{
MainInventarFilterText.text = filterText;
for (int i = 0; i < items.Count; i++)
{
if (uIItems[i].item.GetType() == type)
uIItems[i].transform.parent.gameObject.SetActive(true);
else
uIItems[i].transform.parent.gameObject.SetActive(false);
}
}