107 lines
2.9 KiB
C#
107 lines
2.9 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;
|
|
|
|
[SerializeField] private int currentTargetNPCID;
|
|
|
|
protected override void Awake()
|
|
{
|
|
base.Awake();
|
|
EventBus.Subscribe<NPCINFO>(ShowUINPC);
|
|
//EventBus.Subscribe<NPCDiedEvent>(TryHideUINPC);
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
EventBus.Unsubscribe<NPCINFO>(ShowUINPC);
|
|
EventBus.Unsubscribe<NPCDiedEvent>(TryHideUINPC);
|
|
|
|
}
|
|
|
|
private void ShowUINPC(NPCINFO obj)
|
|
{
|
|
npsUI.gameObject.SetActive(true);
|
|
npsUI.SetText($"{obj.CurrentHealth}/{obj.MaxHealth}",obj.Name,"");
|
|
npsUI.SetHealthImage((float)obj.CurrentHealth / (float)obj.MaxHealth);
|
|
currentTargetNPCID = obj.IDNPC;
|
|
}
|
|
|
|
private void TryHideUINPC(NPCDiedEvent obj)
|
|
{
|
|
if (obj.NPCID != currentTargetNPCID) return;
|
|
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);
|
|
}
|
|
}
|
|
} |