Unity删除所有子物体

    /// <summary>
    /// 删除某Transform下所有子物体
    /// </summary>
    /// <param name="trans"></param>
    private void DeleteAllChildObjs(Transform trans)
    {
    
    
        GameObject[] gameObjects = new GameObject[trans.childCount];
        for (int i = 0; i < trans.childCount; i++)
        {
    
    
            gameObjects[i] = trans.GetChild(i).gameObject;
        }
        for (int i = 0; i < gameObjects.Length; i++)
        {
    
    
            DestroyImmediate(gameObjects[i]);
        }
    }

由于子物体相对于父物体的索引值会随着删除发生变化,所以首先遍历子物体成数组,然后遍历数组摧毁保证万无一失 ^ ^

猜你喜欢

转载自blog.csdn.net/weixin_44003637/article/details/114945021