123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- 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<DamageController, HealthBarUi> healthBars;
- private List<HealthBarUi> unusedHealthBars;
- void OnEnable()
- {
- DamageEvents.OnDamage += OnDamage;
- DamageEvents.OnHeal += OnHeal;
- }
- void OnDisable()
- {
- DamageEvents.OnDamage -= OnDamage;
- DamageEvents.OnHeal -= OnHeal;
- }
- void Start()
- {
- healthBars = new Dictionary<DamageController, HealthBarUi>();
- unusedHealthBars = new List<HealthBarUi>();
- 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<HealthBarUi>();
- }
- 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<DamageController> removeList = new List<DamageController>();
- List<HealthBarUi> moveList = new List<HealthBarUi>();
- foreach(KeyValuePair<DamageController, HealthBarUi> 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]);
- }
- }
- }
- }
|