특정 GameObject의 하위 GameObject / Transform 검색하기

2020. 8. 6. 15:36Unity/수업내용

1) Find 함수로 GameObject의 Name 검색

"ch_01_01"의 GameObject 트리

- 기본적으로 해당 GameObject의 Transform으로 접근하면 Find 함수로 하위 오브젝트 명을 검색할 수 있지만, Find 함수 자체로는 한칸 아래밖에 검색이 되지 않는다.

따라서 만약 기준 Transform이 "ch_01_01"이라면,

 1) Bip01 Footsteps

 2) Bip01 Pelvis

이 두개를 제외하고, 더 하위에 위치한 오브젝트들은 Find 함수로 검색이 되지 않는다는 의미이다.

 

- 이 경우 Find 함수의 인자를 파일 경로 찾듯이 일일이 모든 오브젝트명을 짚어가며 넣는 방법이 있다. 예를 들어 "DummyRHand" 오브젝트를 검색해서 사용하고 싶다면 아래와 같이 사용하면 된다.

 

public GameObject model // <= ch_01_01의 GameObject를 Assign한 것
void start()
{
	var handPivot = model.transform.Find("Bip01/Bip01 Pelvis/Bip01 Spine/Bip01 Spine1/Bip01 Neck/Bip01 R Clavicle/Bip01 R UpperArm/Bip01 R Forearm/Bip01 R Hand/DummyRHand");
}

 

- 위 코드를 보면 알겠지만 진짜 미친짓이 따로 없다. 웬만하면 쓰지 않도록 하자.

 

2) GetComponentsInChildren() 함수를 이용하여 별도의 오브젝트 추출 함수를 제작하여 사용하기

 

- GetComponentsInChildren<T>() 메소드를 사용하면 모든 하위 오브젝트의 Templete 을 가져올 수 있다.

이를 이용하여 별도의 메소드를 입맛에 맞춰 만들어서 사용하면 된다.

예시는 다음과 같다.

Transform GetChildObj(Transform modelTr, string strName)
{
    Transform[] AllData = modelTr.GetComponentsInChildren<Transform>();

    foreach (Transform trans in AllData)
    {
        if (trans.name == strName)
        {
            return trans;
        }
    }
    return null;
}

 

- 위 경우 AllData 배열에 gameObject의 모든 하위 오브젝트가 가지고있는 Transform이 담기게 된다.

그 안에서 strName으로 검색하여 반환하는 함수로 구성할 수 있다

 

- GetComponentsInChildren<T>() 메소드의 경우 GameObject로도, Transform으로도 사용 가능하다. 즉

 1) gameObject.GetComponentsInChildren<T>()

 2) transform.GetComponentsInChildren<T>()

이 두가지가 모두 사용이 가능하다는 의미이다.

'Unity > 수업내용' 카테고리의 다른 글

GPGS(Google Play Game Service) 연동  (0) 2020.08.12
UGUI / NGUI / AssetBundle / CDN 개념 요약  (0) 2020.08.06
MLAgents - RollerBall  (0) 2020.07.14
Coroutine  (0) 2020.05.29
쿠키런 점프 Image  (0) 2020.05.28