unity实现类似dnf血条效果,话不多说,先上效果,再上代码:
//================================代码部分 开始================================
using UnityEngine;
using UnityEngine.UI;
public class HPBar : MonoBehaviour
{
#pragma warning disable 0649
/// <summary>
/// 下一层血条图片
/// </summary>
[SerializeField] private Image nextBar;
#pragma warning disable 0649
/// <summary>
/// 残影图片
/// </summary>
[SerializeField] private Image ghostBar;
#pragma warning disable 0649
/// <summary>
/// 血条图片
/// </summary>
[SerializeField] private Image healthBar;
#pragma warning disable 0649
/// <summary>
/// 血量文本
/// </summary>
[SerializeField] private Text healthText;
#pragma warning disable 0649
/// <summary>
/// 血条颜色循环列表
/// </summary>
[SerializeField] private Color[] colors;
#pragma warning disable 0649
/// <summary>
/// 保证最后一条血是红色
/// </summary>
[SerializeField] private Color redColor;
/// <summary>
/// 血量值
/// </summary>
[SerializeField] private float currentValue;
#pragma warning disable 0649
/// <summary>
/// 怪物信息
/// </summary>
[SerializeField] private Text title;
private int plies;
private readonly float singlePlyValue = 130;
private float barFillAmount;
private int index;
private int counter;
private Image ghostImage;
public static HPBar Ins;
private void Awake()
{
Ins = this;
ghostImage = ghostBar.GetComponent<Image>();
gameObject.SetActive(false);
}
public void SetDamage(float curValue, float maxValue, int lv, string name)
{
gameObject.SetActive(curValue > 0);
if (curValue < 0) curValue = 0;
//设置值
plies = (int)(maxValue / singlePlyValue);
counter = (int)(curValue / singlePlyValue);
ghostBar.fillAmount = healthBar.fillAmount;
currentValue = curValue;
//设置颜色
Color color = healthBar.GetComponent<Image>().color;
ghostImage.color = new Color(color.r, color.g, color.b, 1);
int i = (int)(currentValue / singlePlyValue);
nextBar.gameObject.SetActive(i != 0);
i = plies - i - 1;
i %= colors.Length;
i = i < 0 ? 0 : i;
healthBar.GetComponent<Image>().color = curValue < singlePlyValue ? redColor : colors[i];
nextBar.GetComponent<Image>().color = curValue < singlePlyValue * 2 ? redColor : colors[(i + 1) % colors.Length];
if (i != index)
{
ghostImage.color = colors[i];
ghostBar.fillAmount = 1;
index = i;
}
//设置位置
barFillAmount = currentValue % singlePlyValue / singlePlyValue;
if (barFillAmount == 0)
barFillAmount = currentValue != maxValue ? 0.001f : 1;
healthText.text = $"{counter}/{plies}";
title.text = $"Lv {lv} {name}";
}
private void Update()
{
Color color = ghostImage.color;
color.r += 0.38f;
color.g += 0.38f;
color.b += 0.38f;
color.a = 0.2f;
ghostImage.color = Color.Lerp(ghostImage.color, color, Time.deltaTime * 10);
healthBar.fillAmount = barFillAmount;
if (ghostImage.color.a < 0.25f)
ghostBar.fillAmount = Mathf.Lerp(ghostBar.fillAmount, barFillAmount, Time.deltaTime * 10);
}
}
//================================代码部分 结束================================
面板设置:
源码(QQ):1141243331