[Unity]GetComponentsInChildren

jh Seo·2022년 8월 23일
0

유니티

목록 보기
5/67

GetComponentsInChildren(Type t, bool includeInactive)

public Component[] GetComponentsInChildren(Type t, bool includeInactive);
  • DFS방법을 이용해 부모와 자식오브젝트들의 Type 컴퍼넌트들을 찾아 반환한다.
  • includeInactive는 inactive인 자식 오브젝트도 반환할건지 설정해주는 변수다.
    디폴트는 false로 만약 inactive인 자식오브젝트 반환하려면 true를 설정해줘야한다.

제너릭 버전

public T[] GetComponentsInChildren(bool includeInactive);
public T[] GetComponentsInChildren();

예시는

 //자식오브젝트들을 가진 부모오브젝트
public GameObject buttonsGroup;
//게임오브젝트 배열인 buttons에 buttonsGroup의 자식 오브젝트들을 전부 넣어준다.
GameObject[] buttons= buttonsGroup.GetComponentsInChildren<GameObject>();

이런식으로 사용 가능하다.

GetComponentsInChildren(List<T> results)

public void GetComponentsInChildren(bool includeInactive, List<T> result);
  • 반환값을 채울 List변수를 인자로 넣어주는 방식이다.

  • method 호출할때마다 list object 생성을 막아준다고 한다.
    동일하게 includeInactive는 default로 false다.

  • 인자로 넣어준 list는 반환할 갯수에 맞게 resize되며,
    list 내부에 들어있던 요소들은 새 요소들로 덮어씌워진다.

주의사항

이 함수를 호출한 오브젝트에 반환하려는 컴포넌트가 있다면
자식들의 컴퍼넌트와 호출한 오브젝트의 컴포넌트도 함께 반환한다.

따라서 해당 컴퍼넌트는 반환하지 않으려면 오브젝트의 이름과 비교한다던지 해서
빼야한다.

profile
코딩 창고!

0개의 댓글