저번에 UIManager가 Manager로써의 역할로 부족하다고 작성했었다. 다른 메뉴를 열었을 때 일시정지 메뉴가 나오는 것도 해결할겸해서 UI오브젝트 구성 수정과 UIManager가 더 다양한 역할을 담을 수 있도록 수정하려고 한다.
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor.Rendering;
using UnityEngine;
public class UIManager : MonoBehaviour
{
public static UIManager Instance;
public GameObject currentUI;
private void Awake()
{
if(Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
public void OpenUI(GameObject uiElement)
{
if(currentUI != null)
{
currentUI.SetActive(false);
}
uiElement.SetActive(true);
currentUI = uiElement;
}
public void CloseCurrentUI()
{
if(currentUI != null)
{
currentUI.SetActive(false);
Time.timeScale = 1f;
currentUI = null;
}
public bool IsUIOpen(GameObject uiElement)
{
return currentUI == uiElement;
}
public bool IsAnyUIOpen()
{
return currentUI != null;
}
}
코드를 수정하면서 메뉴를 전환하는 것들을 모두 여기서 실행할 수 있도록 했다. 구조 자체는 복잡하지 않은데... 방향성을 영 엉뚱하게 생각해 시간을 너무 소요해버렸다.
간단하게 설명하자면 UI창을 열 때 현재UI에 매개로 전달할 UI를 전달해주고, UI창을 닫으면 현재 UI를 닫아주는 방식으로 수정했다.
아직 추가는 안했지만 DOTween을 사용해서 UI의 투명도를 조절해 보다 자연스럽게 창이 뜨게끔 기능을 추가할 예정이다.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.InputSystem;
public class UIController : MonoBehaviour
{
[SerializeField] private GameObject pauseUI;
[SerializeField] private GameObject inventory;
private void Start()
{
pauseUI.SetActive(false);
inventory.SetActive(false);
}
public void OnPauseUI(InputAction.CallbackContext callbackContext)
{
if(callbackContext.phase == InputActionPhase.Started)
{
if(UIManager.Instance.currentUI != null && UIManager.Instance.currentUI != pauseUI)
{
UIManager.Instance.CloseCurrentUI();
return;
}
if(UIManager.Instance.IsUIOpen(pauseUI))
{
UIManager.Instance.CloseCurrentUI();
}
else
{
UIManager.Instance.OpenUI(pauseUI);
}
}
}
public void OnInventory(InputAction.CallbackContext callbackContext)
{
if(callbackContext.phase == InputActionPhase.Started)
{
if(UIManager.Instance.IsUIOpen(inventory))
{
UIManager.Instance.CloseCurrentUI();
}
else
{
UIManager.Instance.OpenUI(inventory);
}
}
}
}
UIController쪽도 수정을 했는데, 다른 메뉴가 열려있을 때 일시정지 화면이 나오지 않도록 조건문을 추가해줬다. 현재UI가 비어있고, 해당UI가 일시정지 화면이 아닐 때 종료를 실행하도록 했다. 이렇게 작성해서 설정화면에서 esc를 눌렀을 때 이전화면으로 돌아가는 것이 아니라 바로 메뉴를 비활성화 하게끔 수정했다.