Unity

[Unity] 특정 Object의 자식 Object들 제거법

날아가는기억잡기 2021. 3. 30. 16:00
void DestoryChild(GameObject parentObject)
    {
        Transform[] childList = parentObject.GetComponentsInChildren<Transform>(true);
        if (childList != null)
        {
            for (int i = 1; i < childList.Length; i++)
            {
                if (childList[i] != transform)
                    Destroy(childList[i].gameObject);
            }
        }
    }

위 함수처럼 작성을 하면 parentObject의 자식 오브젝트들을 모두 제거해준다.

여기서 for 문 내의 i값을 0이 아닌 1부터 시작하는 이유는 childList[0]에는 parentObject가 담겨있기 때문이다.