[Unity] Instantiate시 깔끔하게 정리하기

Yerin·2023년 7월 27일
0

여러개의 팝업을 띄운다고 할 때

 void Start()
    {
        for (int i = 0; i < 8; i++)
            Managers.UI.ShowPopupUI<UI_Button>();   
    }

아래 사진처럼 생성이 되어 지저분해 보이는 경우가 있다.

UIManager.cs

UIManager 스크립트에서 아래와 같이 부모 오브젝트를 찾아 아래에 생성하도록 코드를 짠다.
부모 오브젝트가 없을 경우 만들어주는 작업도 추가한다.

public T ShowPopupUI<T>(string name = null) where T : UI_Popup
    {

       if (string.IsNullOrEmpty(name))
            name = typeof(T).Name;

        GameObject go = Managers.Resource.Instantiate($"UI/Popup/{name}");
        T popup = Util.GetOrAddComponent<T>(go);
        _popupStack.Push(popup);

        GameObject root = GameObject.Find("@UI_Root");
        if (root == null)
        {
            root = new GameObject { name = "@UI_Root" };
        }
        
        go.transform.SetParent(root.transform);

        return popup;  
    }

이제 UI_Root라는 오브젝트 안에 버튼 오브젝트들이 추가되는 것을 볼 수 있다.

profile
재밌는 코딩 공부

0개의 댓글