using System.Collections; using System.Collections.Generic; using UnityEngine; using Sirenix.OdinInspector; namespace KairoEngine.CharacterSystem { public class HealthBarController : MonoBehaviour { public GameObject healthBarUiPrefab; public Transform canvasParent; private Dictionary healthBars; private List unusedHealthBars; void OnEnable() { DamageEvents.OnDamage += OnDamage; DamageEvents.OnHeal += OnHeal; } void OnDisable() { DamageEvents.OnDamage -= OnDamage; DamageEvents.OnHeal -= OnHeal; } void Start() { healthBars = new Dictionary(); unusedHealthBars = new List(); unusedHealthBars.Add(CreateHealthBar()); } void Update() { RemoveUnused(); } private void OnDamage(DamageData damageData) { //Debug.Log("Showing Health Bar for " + damageController.character.unique_name); HealthBarUi healthBar = GetHealthBarFor(damageData.damageController); healthBar.Setup(damageData.damageController); healthBar.gameObject.SetActive(true); } private void OnHeal(DamageController damageController, int damage) { //Debug.Log("Showing Health Bar for " + damageController.character.unique_name); HealthBarUi healthBar = GetHealthBarFor(damageController); healthBar.Setup(damageController); healthBar.gameObject.SetActive(true); } private HealthBarUi CreateHealthBar() { GameObject obj = Instantiate(healthBarUiPrefab, canvasParent); obj.SetActive(false); return obj.GetComponent(); } private HealthBarUi GetHealthBarFor(DamageController damageController) { // Find Health Bar in use HealthBarUi healthBar; if(healthBars.TryGetValue(damageController, out healthBar)) { if(healthBar != null) return healthBar; } // Look for Health Bar in unused if(unusedHealthBars.Count > 0) { healthBar = unusedHealthBars[unusedHealthBars.Count - 1]; unusedHealthBars.RemoveAt(unusedHealthBars.Count - 1); } else { // Create new Health Bar healthBar = CreateHealthBar(); } healthBars.Add(damageController, healthBar); return healthBar; } private void RemoveUnused() { List removeList = new List(); List moveList = new List(); foreach(KeyValuePair healthBar in healthBars) { if(healthBar.Value.gameObject.activeSelf == false) { removeList.Add(healthBar.Key); moveList.Add(healthBar.Value); } } for (int i = 0; i < removeList.Count; i++) { healthBars.Remove(removeList[i]); unusedHealthBars.Add(moveList[i]); } } } }