您最多选择25个主题
主题必须以中文或者字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
77 行
1.6 KiB
77 行
1.6 KiB
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class UIHealthBarManager : MonoBehaviour
|
|
{
|
|
Transform target;
|
|
int maxHealth=0;
|
|
int currentHealth=0;
|
|
[SerializeField] private Slider _healthBar = default;
|
|
|
|
[Header("Listening to")]
|
|
[SerializeField] private IntEventChannelSO _setHealthBar = default;
|
|
[SerializeField] private IntEventChannelSO _inflictDamage = default;
|
|
[SerializeField] private IntEventChannelSO _restoreHealth = default;
|
|
|
|
private void OnEnable()
|
|
{
|
|
|
|
if((GetComponent<Canvas>()!=null)&&(Camera.main!=null))
|
|
{
|
|
GetComponent<Canvas>().worldCamera = Camera.main;
|
|
target = Camera.main.transform;
|
|
|
|
}
|
|
}
|
|
private void Start()
|
|
{
|
|
if (_setHealthBar != null)
|
|
{
|
|
_setHealthBar.OnEventRaised += SetHealthBar;
|
|
}
|
|
if (_inflictDamage != null)
|
|
{
|
|
_inflictDamage.OnEventRaised += InflictDamage;
|
|
}
|
|
if (_restoreHealth != null)
|
|
{
|
|
_restoreHealth.OnEventRaised += RestoreHealth;
|
|
}
|
|
}
|
|
public void SetHealthBar(int _maxHealth)
|
|
{
|
|
maxHealth = _maxHealth;
|
|
currentHealth = _maxHealth;
|
|
setSlider();
|
|
|
|
}
|
|
public void InflictDamage(int _damage)
|
|
{
|
|
currentHealth -= _damage;
|
|
setSlider();
|
|
}
|
|
public void RestoreHealth(int _healthToAdd)
|
|
{
|
|
currentHealth += _healthToAdd;
|
|
setSlider();
|
|
}
|
|
|
|
void setSlider()
|
|
{
|
|
//clamp current value
|
|
currentHealth = Mathf.Clamp(currentHealth, 0, maxHealth);
|
|
//find new slider value
|
|
float sliderValue = 0;
|
|
sliderValue = currentHealth / maxHealth;
|
|
_healthBar.value = sliderValue;
|
|
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (target != null)
|
|
transform.LookAt(target, Vector3.down);
|
|
}
|
|
}
|