반응형

안녕하세요.

오늘은 하이라이키(Hierarchy)에서 순위 변경하는 방법에 대해 알아보도록 하겠습니다.

UI 등 같은 위치에 겹치게 되면 하이라이키(Hierarchy)의 나중에 있는 게 더 위로 나옵니다.

물론 순서를 바꾸면, 순위를 바꿀 수 있습니다.

하지만, 실행 중에 변경하려면 스크립트를 이용해야 합니다.

스크립트에서 다음 함수를 사용할 수 있습니다.

Transform.SetAsLastSibling
해당 오브젝트의 순위를 마지막으로 변경(가장 나중에 출력되므로 겹쳐졋을 경우 앞으로 나옵니다.)

Transform.SetAsFirstSibling
해당 오브젝트의 순위를 처음으로 변경(가장 처음 출력되므로 겹쳐졋을 경우 가려집니다.)

Transform.SetSiblingIndex(int nIndex)
nIndex를 매개변수를 넣어서 순위를 지정합니다.(0이 처음입니다.)

Transform.GetSiblingIndex()
해당 오브젝트의 순위를 얻어옵니다.

 

예제

일단 이미지 오브젝트를 생성하고, blue, red로 지정하겠습니다.

그리고 스크립트가 들어갈 오브젝트를 하나 만듭니다.(ScriptObject)

스크립트에 다음과 같이 입력하면 현재 오브젝트의 순위값을 알 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class GameManger : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        GameObject goRed = GameObject.Find("Canvas/red");
        GameObject goBlue = GameObject.Find("Canvas/blue");
 
        Debug.Log("goRed : " + goRed.transform.GetSiblingIndex());
        Debug.Log("goBlue : " + goBlue.transform.GetSiblingIndex());
    }
}
 
cs

출력값은 다음과 같습니다.

빨간 사각형이 나중에 나오기 때문에 1로 표기 되었습니다.

순위를 변경할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class GameManger : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        GameObject goRed = GameObject.Find("Canvas/red");
        GameObject goBlue = GameObject.Find("Canvas/blue");
 
        Debug.Log("before goRed : " + goRed.transform.GetSiblingIndex());
        Debug.Log("before goBlue : " + goBlue.transform.GetSiblingIndex());
 
        goRed.transform.SetSiblingIndex(0);
        Debug.Log("after goRed : " + goRed.transform.GetSiblingIndex());
        Debug.Log("after goBlue : " + goBlue.transform.GetSiblingIndex());
    }
}
cs

출력값

16번째 줄 "goRed.transform.SetSiblingIndex(0);" 대신에 "goRed.transform.SetAsFirstSibling();", "goBlue.transform.SetAsLastSibling();"를 넣으면 같은 결과를 얻을 수 있습니다. 

 

반응형

+ Recent posts