using System; using System.Collections.Generic; using BrewMonster; using UnityEngine; public class CECUIManager : MonoSingleton { [SerializeField] private Transform uiRoot; // nơi chứa UI được spawn (Canvas hoặc Transform) [SerializeField] private List uiPrefabs; // drag các prefab UI vào đây private readonly Dictionary _spawnedUIs = new(); [SerializeField] private HUDNPC npsUI; protected override void Awake() { base.Awake(); EventBus.Subscribe(ShowUINPC); } private void OnDestroy() { EventBus.Unsubscribe(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); } /// /// Lấy hoặc spawn UI mới nếu chưa có /// public T ShowUI() 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ìm prefab phù hợp var prefab = uiPrefabs.Find(p => p.GetComponent() != 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(); } /// /// Ẩn UI (disable thay vì destroy) /// public void HideUI() where T : Component { var type = typeof(T); if (_spawnedUIs.TryGetValue(type, out var uiGo)) { uiGo.SetActive(false); } } /// /// Kiểm tra UI có đang active không /// public bool IsUIActive() where T : Component { var type = typeof(T); return _spawnedUIs.TryGetValue(type, out var uiGo) && uiGo.activeSelf; } /// /// Ẩn tất cả UI hiện tại /// public void HideAll() { foreach (var kv in _spawnedUIs) { kv.Value.SetActive(false); } } }