Unity實(shí)現(xiàn)血條緩降效果

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
??public Image hpImg; // 血量顯示的Image控件
??public Image hpEffectImg; // 血量變化效果的Image控件
??public float maxHp = 100f; // 最大血量
??public float currentHp; // 當(dāng)前血量
??public float buffTime = 0.5f; // 血條緩沖時(shí)間
??private Coroutine updateCoroutine;
??private void Start()
??{
????currentHp = maxHp; // 初始時(shí),為滿(mǎn)血
????UpdateHealthBar(); // 更新血條顯示
??}
??public void SetHealth(float health)
??{
????// 限制血量在0到最大血量之間
????currentHp = Mathf.Clamp(health, 0f, maxHp);
????// 更新血條顯示
????UpdateHealthBar();
????// 當(dāng)血量小于等于0時(shí),觸發(fā)死亡效果
????if (currentHp <= 0)
????{
??????// Die();
????}
??}
??// 死亡函數(shù)
??private void Die()
??{
????// 在此處添加死亡相關(guān)的代碼
??}
??// 在禁用對(duì)象時(shí)停止協(xié)程
??private void OnDisable()
??{
????if (updateCoroutine != null)
????{
??????StopCoroutine(updateCoroutine);
????}
??}
??// 增加血量
??public void IncreaseHealth(float amount)
??{
????SetHealth(currentHp + amount);
??}
??// 減少血量
??public void DecreaseHealth(float amount)
??{
????SetHealth(currentHp - amount);
??}
??// 更新血條顯示
??private void UpdateHealthBar()
??{
????// 根據(jù)當(dāng)前血量與最大血量計(jì)算并更新血條顯示
????hpImg.fillAmount = currentHp / maxHp;
????// 緩慢減少血量變化效果的填充值
????if (updateCoroutine != null)
????{
??????StopCoroutine(updateCoroutine);
????}
????updateCoroutine = StartCoroutine(UpdateHpEffect());
??}
??// 協(xié)程,用于實(shí)現(xiàn)緩慢減少血量變化效果的填充值
??private IEnumerator UpdateHpEffect()
??{
????float effectLength = hpEffectImg.fillAmount - hpImg.fillAmount; // 計(jì)算效果長(zhǎng)度
????float elapsedTime = 0f; // 已過(guò)去的時(shí)間
????while (elapsedTime < buffTime && effectLength != 0)
????{
??????elapsedTime += Time.deltaTime; // 更新已過(guò)去的時(shí)間
??????hpEffectImg.fillAmount = Mathf.Lerp(hpImg.fillAmount + effectLength, hpImg.fillAmount, elapsedTime / buffTime); // 使用插值函數(shù)更新效果填充值
??????yield return null;
????}
????hpEffectImg.fillAmount = hpImg.fillAmount; // 確保填充值與血條填充值一致
??}
}