Hello,
I want to make a dynamic shop UI, but when changing the category I want to, obviously, clear whatever was previously in it. So I am iterating through all children, which for some reason causes an InvalidCastException. I have used the same loop in a different part of my code, but there it doesn’t throw the exception.
Code:
public void LoadForCategory(BuildingCategory category)
{
foreach(GameObject child in this.transform) // This is line 12 where the error occurs.
{
Destroy(child);
}
List<Building> buildings = new List<Building>();
if(category == BuildingCategory.DECORATION)
{
buildings = BuildingsRegistry.self.FilterByCategories(new BuildingCategory[] { BuildingCategory.DECORATION });
}
foreach(Building building in buildings)
{
GameObject newButton = Instantiate(buildingItemPrefab);
newButton.transform.Find("PriceText").GetComponent<Text>().text = "$ " + building.price;
newButton.transform.Find("PreviewImage").GetComponent<Image>().sprite = building.preview;
newButton.transform.parent = transform;
}
}
The error:
InvalidCastException: Specified cast is not valid.
BuildingItemList.LoadForCategory (BuildingCategory category) (at Assets/Scripts/Mechanics/Building/UI/BuildingItemList.cs:12)
BuildingCategoryButton.OnClick () (at Assets/Scripts/Mechanics/Building/UI/BuildingCategoryButton.cs:12)
UnityEngine.Events.InvokableCall.Invoke () (at <f98083cbc97e4fa0a4ef2f523feff5e1>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <f98083cbc97e4fa0a4ef2f523feff5e1>:0)