Unity deletes all child objects

    /// <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]);
        }
    }

Since the index value of the child object relative to the parent object will change with the deletion, first traverse the child object into an array, and then traverse the array to destroy it to ensure foolproof ^ ^

Guess you like

Origin blog.csdn.net/weixin_44003637/article/details/114945021