1.创建一个Canvas,在它下面创建一个空物体,然后在空物体下创建一个Image导入白色图片当做背景(颜色调成黑色)然后继续创建一个Image导入红色图片当做血量(颜色调成红色)然后创建一个Text当做血量变化的百分值(100%初始血量)。
创建一个代码HealthBar如下:挂载到空物体上。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;//引入命名空间
public class HealthBar : MonoBehaviour {
//1红色血条
Image redImage;
//1当前血值
float currentHealth = 100;
//1最大血值
float maxHealth = 100;
//1对应文本
Text txtValue;
//2是否加血
bool IsAddHealth;
//2插值
float differ;
void Start () {
//1通过名字查找红色血条组件,对应关系
redImage = this.transform.Find("RedBar").GetComponent<Image>();
//1通过名字查找文本组件,对应关系
txtValue = this.transform.Find("TextLiftValue").GetComponent<Text>();
}
//1自定义修改血条的方法
/* public void ChangValue(float amount)
{
//1修改血值
currentHealth += amount;
//1边界限制
currentHealth = Mathf.Clamp(currentHealth,0,maxHealth);
//1血值图片的填充比例
redImage.fillAmount = currentHealth / maxHealth;
//1文本显示
txtValue.text = currentHealth.ToString();
}*/
//2自定义修改血条的方法
public void ChangValue(float amount)
{
//2判断加血还是减血,IsAddHealth为1意味加血,IsAddHealth为0意味减血
IsAddHealth = amount > 0;
//1修改血值
currentHealth += amount;
//1边界限制
currentHealth = Mathf.Clamp(currentHealth, 0, maxHealth);
//2存放填充比例,新的插值
float newRatlo = currentHealth / maxHealth;
if(IsAddHealth)//2加血
{
//2逐渐变化的插值
differ = newRatlo - redImage.fillAmount;
}
else//2减血
{
//2逐渐变化的插值
differ = redImage.fillAmount - newRatlo;
}
//1文本显示
txtValue.text = currentHealth.ToString();
}
public float unit = 0.5f;//2每帧的变化量
//2渐变效果
private void Effect()
{
//2有变化的时候实现渐变
if (differ > 0)
{
//2平衡插值
differ -= unit * Time.deltaTime;
//2加血
if (IsAddHealth)
redImage.fillAmount += unit * Time.deltaTime;
//2减血
else
redImage.fillAmount -= unit * Time.deltaTime;
}
}
// Update is called once per frame
void Update () {
Effect();
}
//1重写OnGUI()方法
void OnGUI()
{
//1显示按钮
if (GUILayout.Button("轻伤"))
{
ChangValue(-10);
}
if (GUILayout.Button("重伤"))
{
ChangValue(-30);
}
if (GUILayout.Button("小补"))
{
ChangValue(10);
}
if (GUILayout.Button("大补"))
{
ChangValue(30);
}
}
}