我有以下脚本,它附加到游戏对象并在我单击编辑器中的按钮时运行:
public void ClearChildren() {
Debug.Log(transform.childCount);
float i = 0;
foreach (Transform child in transform) {
i += 1;
DestroyImmediate(child.gameObject);
}
Debug.Log(transform.childCount);
}
它表明原始 childCount
是 13,最终值为 6。此外,如果我在每次迭代中打印出所有 i
,我会看到值 0-6,表明循环只运行了 7 次,而不是预期的 13 次。
我怎样才能删除所有 child ,使最终值为 0?作为引用,我试图删除的 child 是由供应商脚本自动创建的。我还在 [ExecuteInEditMode]
中运行此脚本,以了解它的值(value)。
以下脚本具有相同的行为;如果 childCount
从 4 开始,那么它在 2 结束:
public void ClearChildren() {
Debug.Log(transform.childCount);
for (int i = 0; i < transform.childCount; i++) {
Transform child = transform.GetChild(i);
DestroyImmediate(child.gameObject);
}
Debug.Log(transform.childCount);
}
如果我尝试以下操作,我会收到一个指向 foreach
行的运行时错误,上面写着“InvalidCastException:无法从源类型转换为目标类型。”
public void ClearChildren() {
Debug.Log(transform.childCount);
foreach ( GameObject child in transform) {
DestroyImmediate(child);
}
Debug.Log(transform.childCount);
}
最佳答案
此处的其他解决方案似乎设计过度。我想要代码占用空间更小的东西。这会破坏对象的直接子对象及其所有后代。
while (transform.childCount > 0) {
DestroyImmediate(transform.GetChild(0).gameObject);
}
关于c# - 如何循环并销毁Unity中游戏对象的所有 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46358717/