微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何在Unity中循环并销毁游戏对象的所有子项?

我有以下脚本附加到游戏对象并在我单击编辑器中的按钮时运行:

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次.

如何删除所有子项,使最终值为0?作为参考,我试图删除的孩子是由供应商脚本自动创建的.我也在[ExecuteInEditMode]中运行这个脚本以获得它的价值.

以下脚本具有相同的行为;如果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);
}

解决方法:

问题是您正在尝试在访问它们时删除for循环中的Object.

这是你应该做的:

1.查找所有Child对象并将它们存储在一个数组中

2.在另一个循环中销毁它们

public void ClearChildren()
{
    Debug.Log(transform.childCount);
    int i = 0;

    //Array to hold all child obj
    GameObject[] allChildren = new GameObject[transform.childCount];

    //Find all child obj and store to that array
    foreach (Transform child in transform)
    {
        allChildren[i] = child.gameObject;
        i += 1;
    }

    //Now destroy them
    foreach (GameObject child in allChildren)
    {
        DestroyImmediate(child.gameObject);
    }

    Debug.Log(transform.childCount);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐