u3D开发学习之路--创建多层血条脚本

实现游戏中Boss掉血的方法,该方法可以创建多层血条。如有写的不好的地方请大家指出

1、首先在Hierarchy面板中创建Canvas画布;


2、在Canvas下创建空物体作为血条;


3、在HealthBar下创建image的UI;


4、创建BossHealthBar脚本并拖到HealthBar上,编写脚本;

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

///
///多层血条类
///
public class BossHealthBar : MonoBehaviour
{
	[System.Serializable]//序列化
	public class Bars
	{
		public Color first;
		public Color second;
	}
	public Bars[] healthBarArray;
	public Image ImageTop;
	public Image ImageMiddle;
	public Image ImageBotton;
	public Text TextValue;
	
	float currentHP = 100f;
	float ratio=1;
	public float fadingSpeed;
	int index = 0;
	float maxHP = 100f;
	void Start()
	{
		Init();//在Start方法中调用初始化
	}
	
	private void Init()
	{
		ImageTop.fillAmount = 1f;
		ImageMiddle.fillAmount = 1f;
		ImageTop.color = healthBarArray[index].first;
		ImageMiddle.color = healthBarArray[index].second;
		ImageBotton.color = healthBarArray[index + 1].first;
		currentHP = 100f;
	}
	private void InitEnd()
	{
		ImageTop.fillAmount = 1f;
		ImageMiddle.fillAmount = 1f;
		ImageTop.color = healthBarArray[index].first;
		ImageMiddle.color = healthBarArray[index].second;
		ImageBotton.color = Color.black;
		currentHP = 100f;
	}
	void OnGUI()//在OnGUI中进行调试
	{
		if (GUILayout.Button("减血"))
		{
			hurtOrRecoverValue(-10f);
		}
	}
	void Update()
	{
		
		ImageMiddle.fillAmount = Mathf.Lerp(ImageMiddle.fillAmount, ratio, fadingSpeed);//在Update方法中不断调用
	}
	private void hurtOrRecoverValue(float value)
	{
		if (ImageTop.fillAmount == 0f && index == healthBarArray.Length - 1)//当最后一层血条减为0的时候不再计算
		{
			value = 0;
		}
		currentHP += value;
		TextValue.text = ((maxHP * (healthBarArray.Length - index)) - (maxHP- currentHP)).ToString();
		currentHP = Mathf.Clamp(currentHP, 0, maxHP);
		ImageTop.fillAmount = currentHP / maxHP;
		
		if (ImageTop.fillAmount == 0f && index < healthBarArray.Length - 1)//当层血条减为0的时候并且没有到达最后一层的时候
		{
			index++;
			if (index == healthBarArray.Length - 1)
			{
				InitEnd();//在最后一层中重新初始化,避免数组溢出
			}
			else
				Init();
		}
		ratio = currentHP / maxHP;
	}
}

需要注意的地方:有很多方法必须要在Update方法中调用,否则将一帧一帧的播放。例如有很多类中的Lerp、MoveTowards方法。

你可能感兴趣的:(Unity3D)