【Unity】销毁子物体的两种方法

销毁所有子物体后,获取子物体的数量为0

如果在同一帧内需要增加子物体并统计新的子物体的数量可以使用这个方法

1
2
3
4
5
6
for (int i = 0; i < coneten.childCount; i++)
{
DestroyImmediate(content.GetChild(0).gameObject);
Debug.Log(content.childCount); # 输出的值会慢慢的变小,直至变为0
}
Debug.Log(content.childCount); # 输出为0

注意:这里的for循环获取子物体的方法是GetChild(o)

销毁所有子物体后,获取子物体的数量为销毁前的数量

1
2
3
4
5
6
for (int i = 0; i < content.childCount; i++)
{
Destroy(content.GetChild(i).gameObject);
Debug.Log(content.childCount); # 输出的一直是销毁前的子物体数量
}
Debug.Log(content.childCount); # 输出的是销毁前的子物体数量

1
2
3
4
5
6
foreach (RectTransform item in content)
{
Destroy(item.gameObject);
Debug.Log(content.childCount); # 输出的一直是销毁前的子物体数量
}
Debug.Log(content.childCount); # 输出的是销毁前的子物体数量

注意:这里的for循环中获取子物体的方法是GetChild(i),这种for循环方式和forecho是一样的

销毁子物体错误的方法

这种方法销毁不干净子物体

1
2
3
4
5
foreach (RectTransform item in content)
{
DestoryImmediate(item.gameObject);
}
Debug.Log(content.childCount);