Files
test/Assets/Scripts/CECUIManager.cs
T
2025-11-05 18:13:46 +07:00

111 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using BrewMonster;
using UnityEngine;
public class CECUIManager : MonoSingleton<CECUIManager>
{
[SerializeField] private Transform uiRoot; // nơi chứa UI được spawn (Canvas hoặc Transform)
[SerializeField] private List<GameObject> uiPrefabs; // drag các prefab UI vào đây
private readonly Dictionary<System.Type, GameObject> _spawnedUIs = new();
[SerializeField] private HUDNPC npsUI;
CECGameUIMan gameUI;
protected override void Awake()
{
base.Awake();
EventBus.Subscribe<NPCINFO>(ShowUINPC);
}
private void OnDestroy()
{
EventBus.Unsubscribe<NPCINFO>(ShowUINPC);
}
private void ShowUINPC(NPCINFO obj)
{
npsUI.gameObject.SetActive(true);
npsUI.SetText($"{obj.CurrentHealth}/{obj.MaxHealth}",obj.Name,"");
}
private void HideUINPC(NPCINFO obj)
{
npsUI.gameObject.SetActive(false);
}
/// <summary>
/// Lấy hoặc spawn UI mới nếu chưa có
/// </summary>
public T ShowUI<T>() where T : Component
{
var type = typeof(T);
// Nếu đã spawn rồi thì bật lại
if (_spawnedUIs.TryGetValue(type, out var uiGo))
{
uiGo.SetActive(true);
return uiGo.GetComponent<T>();
}
// Tìm prefab phù hợp
var prefab = uiPrefabs.Find(p => p.GetComponent<T>() != null);
if (prefab == null)
{
Debug.LogError($"Không tìm thấy prefab chứa component {type.Name}");
return null;
}
// Spawn mới
var instance = Instantiate(prefab, uiRoot ? uiRoot : transform);
instance.name = $"{type.Name}_UI";
_spawnedUIs[type] = instance;
instance.SetActive(true);
return instance.GetComponent<T>();
}
/// <summary>
/// Ẩn UI (disable thay vì destroy)
/// </summary>
public void HideUI<T>() where T : Component
{
var type = typeof(T);
if (_spawnedUIs.TryGetValue(type, out var uiGo))
{
uiGo.SetActive(false);
}
}
/// <summary>
/// Kiểm tra UI có đang active không
/// </summary>
public bool IsUIActive<T>() where T : Component
{
var type = typeof(T);
return _spawnedUIs.TryGetValue(type, out var uiGo) && uiGo.activeSelf;
}
/// <summary>
/// Ẩn tất cả UI hiện tại
/// </summary>
public void HideAll()
{
foreach (var kv in _spawnedUIs)
{
kv.Value.SetActive(false);
}
}
// If current UI manager is INGAME manager, this function return it's interface
public CECGameUIMan GetInGameUIMan()
{
if(gameUI == null)
{
gameUI = new CECGameUIMan();
}
return gameUI;
}
}