Unity에서 비활성화된 자식 오브젝트까지 가져오는 방법 (GetComponentsInChildren 활용법)

🎯 Unity에서 비활성화된 자식 오브젝트까지 가져오는 방법 (GetComponentsInChildren 활용법)

Unity에서 게임 오브젝트의 자식 컴포넌트를 가져올 때 GetComponentsInChildren<T>()을 자주 사용합니다.
하지만 이 메서드는 기본적으로 비활성화된(비활성) 자식 오브젝트는 무시합니다.

그래서! 비활성화된 오브젝트도 포함해서 가져오려면 한 가지 설정이 필요합니다.


📌 기본 사용법

Button[] buttons = parent.GetComponentsInChildren<Button>();

이 코드는 parent 오브젝트의 자식 중 활성화된(Button 컴포넌트를 가진) 오브젝트만 가져옵니다.
즉, SetActive(false) 상태인 자식은 포함되지 않아요.


✅ 비활성 자식도 포함하는 방법

Button[] buttons = parent.GetComponentsInChildren<Button>(true);

true를 인자로 넘기면 includeInactive 옵션이 활성화되어,
비활성화된 자식 오브젝트까지 포함해서 모두 가져올 수 있습니다.


🧪 예제 코드

public GameObject AnswerBoard;
public List<Button> AnswersBtnList = new List<Button>();

void Start()
{
    AnswersBtnList.Clear(); // 중복 방지
    Button[] buttons = AnswerBoard.GetComponentsInChildren<Button>(true); // ← 핵심은 여기!
    AnswersBtnList.AddRange(buttons);

    Debug.Log($"찾은 버튼 개수: {AnswersBtnList.Count}");
}

💡 true를 꼭 넣어야 비활성 오브젝트도 포함됩니다!


🛠 언제 써야 할까?

  • UI 구성요소가 기본적으로 SetActive(false) 상태로 숨겨져 있을 때
  • 오브젝트 풀링에서 꺼진 상태의 오브젝트를 참조해야 할 때
  • 씬 초기화 시, 숨겨진 오브젝트도 모두 구성해야 할 때

⚠ 주의할 점

  • includeInactive = true를 쓰면 전체 자식 오브젝트를 모두 검사하므로, 성능상 꼭 필요할 때만 사용하는 게 좋습니다.
  • parent가 비활성 상태더라도 자식 오브젝트는 정상적으로 검색됩니다.

🧾 정리 요약

호출 방식 비활성 오브젝트 포함 여부

GetComponentsInChildren<T>() ❌ 포함 안 됨
GetComponentsInChildren<T>(true) ✅ 포함됨

✨ 마무리

Unity의 GetComponentsInChildren 함수는 아주 유용하지만,
비활성 오브젝트는 기본적으로 무시된다는 점을 꼭 기억하세요.
간단히 true 옵션만 추가해도 모든 자식 오브젝트를 안전하게 가져올 수 있습니다 😊