[Unity] UI Manager

Yerin·2023년 7월 27일
0

UI Manager를 만들어 Popup의 Sort Order를 관리하자.

UIManager.cs

popup을 띄우고 닫는 코드를 작성한다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIManager 
{
    int _order = 0;

    Stack<UI_Popup> _popupStack = new Stack<UI_Popup>();

    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/Popul/{name}");

        T popup = Util.GetOrAddComponent<T>(go);
        _popupStack.Push(popup);
        

        return popup;
    }

    public void ClosePopupUI()
    {
        if (_popupStack.Count == 0)
            return;

        UI_Popup popup = _popupStack.Pop();
        Managers.Resource.Destroy(popup.gameObject);
        
        popup = null;
        _order--;
    }
}

이제 코드가 제대로 실행이 되는 지 테스트해보자.

Player 스크립트에 아래 코드를 추가해준다.

 void Start()
    {
        Managers.UI.ShowPopupUI<UI_Button>();
    }

이제 실행버튼을 누르면 UI_Button이 Clone 되어 생성되는 것을 볼 수 있다.

아래와 같이 코드를 작성하면 삭제도 되는 것을 알 수 있다.
마지막에 띄운 팝업이 삭제된다.

 void Start()
    {
        Managers.UI.ShowPopupUI<UI_Button>();
        Managers.UI.ClosePopupUI();
profile
재밌는 코딩 공부

0개의 댓글