Iterating through children causes InvalidCastException
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)
Answer by GoldenretriverYT · Jan 16 at 03:37 PM
Update: I spotted my mistake by changing GameObject to dynamic and then doing GetType().Name, which turned out to be RectTransform and not GameObject.
Your answer
![](https://koobas.hobune.stream/wayback/20220613051742im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Child GameObject doesn't follow parent transform 0 Answers
Can't get Child's Child 0 Answers
Loop through children and their children 1 Answer
Notify a script that a transform has changed its parent 1 Answer
Randomly sort siblings 0 Answers