思路:角色下添加一个 Canvas,在Canvas下添加血条即可
添加Canvas、血条,血条的Scale设置为0.006大小就差不多
Canvas下添加一个脚本来控制血条,因为血条在角色身上所以会跟随角色旋转,所以我们要让它一直朝向屏幕
void Update () { transform.rotation = Camera.main.transform.rotation; }
掉血特效的实现 ①先做好一个显示掉血数字的prefab ②构建一个对象池 ③通过对象池获取prefab并添加特效,之后回收。
//对象池
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
public Queue<GameObject> pool = new Queue<GameObject>();//使用队列,先进先出,避免连续生成同一个对象
GameObject model; //预制体,就是一个image,用来显示数字
private Transform m_wordParent;
private void Awake()
{
m_wordParent = GameObject.Find("LoseHpNode").transform;
}
public void Expand(int count)
{
GameObject obj = null;
for (int index = 0; index < count; index++)
{
obj = Instantiate(Resources.Load<GameObject>("Prefabs/LoseHp"));
obj.transform.SetParent(m_wordParent);
obj.SetActive(false);
pool.Enqueue(obj);
}
}
public GameObject GetObject()//得到一个对象
{
if (pool.Count <= 0)//池子没有对象,扩展
Expand(20);
GameObject obj = pool.Dequeue();//得到队列底部的对象
obj.SetActive(true);
return obj;
}
public void Recovery(GameObject obj)//回收一个对象
{
obj.SetActive(false);
obj.transform.SetParent(m_wordParent);
if (pool.Contains(obj))//重复的不添加?。。。
return;
pool.Enqueue(obj);
}
}
//掉血效果的实现
public void LoseHp(float damage)
{
GameObject obj = m_pool.GetObject();
obj.transform.SetParent(m_hpNode);
obj.GetComponent<Text>().text = "-" + damage;
obj.GetComponent<RectTransform>().localPosition = new Vector3(0, 0, 0);
obj.transform.localRotation = Quaternion.identity;
StartCoroutine(UpNumber(obj));//使实例的物体上升
}
IEnumerator UpNumber(GameObject obj)
{
yield return new WaitForSeconds(0.2f);
obj.GetComponent<RectTransform>().DOLocalMove(new Vector3(0, 2f, 0), 0.5f);//用tween将数字移动到指定位置
// obj.GetComponent<Renderer>().material.DOFade(0, 1);
yield return new WaitForSeconds(1);//1秒钟后隐藏或者销毁
m_pool.Recovery(obj);
}