개발괴발 공부

재귀 호출 (Recursive)

방프 2021. 4. 22. 21:48

재귀 호출 (recursive)

자신의 함수 안에서 자신을 호출하는 것이다.

 

Test(10); // 사용시

void Test(int n){
	if( n <= 0)
		return;
	Test(n++);
}

 


void Start()
{
    DisplayAllGameObjectName(originTr);

    Transform findTr = FindChildByName(originTr, findName);
    if (findTr != null)
        Debug.Log("찾는 오브젝트가 자식에 있다.");
    else
        Debug.Log("찾는 오브젝트가 자식에 없다.");
}

/*****************************************************
// 자신의 자식으로 추가된 모든 게임오브젝트 이름 출력
******************************************************/
int childNum;
void DisplayAllGameObjectName(Transform tr)
{
    int count = tr.childCount;

    for (int i = 0; i < count; i++)
    {
        Debug.Log($"{tr.name}의 자식 이름 : {tr.GetChild(i).name}");
        DisplayAllGameObjectName(tr.GetChild(i));
    }
}

/*****************************************************
// 매개변수로 전달된 게임오브젝트가 자식에 있는지 검사 후 리턴
******************************************************/
Transform FindChildByName(Transform tr, string strFind)
{
    if (tr.name.Equals(strFind))
        return tr;

    for(int i=0; i<tr.childCount; i++)
    {
        Transform tf = FindChildByName(tr.GetChild(i), strFind);

        if (tf != null)
            return tf;
    }

    return null;
}