Unity 实现血条跟随

首先在Canvas中制作一个UI来做为血条的父物体

(1)在Canvas下创建空物体改名为DynamicPanel,将其铺满整个屏幕。在DynamicPanel创建空物体命名为ItemHPRoot作为所有血条的父物体,锚点定在左下角

Unity 实现血条跟随_第1张图片

 

(2)在ItemHPRoot下制作血条,制作完后拖入Resources文件中作为预制体,删除ItemHPRoot下的ItemHP

Unity 实现血条跟随_第2张图片

(3)给血条添加脚本

public class ItemHP : MonoBehaviour {
    private RectTransform rect;
    //要跟随的物体
    private Transform rootTrans;

    private void Update() {
        //将 position 从世界空间变换为屏幕空间
        Vector3 screenPos = Camera.main.WorldToScreenPoint(rootTrans.position);
        //此 RectTransform 的轴心相对于锚点参考点的位置
        rect.anchoredPosition = screenPos;
    }
    //初始化函数
    public void InitItemInfo(Transform trans) {
        rect = transform.GetComponent();
        rootTrans = trans;
    }
}

(4)给DynamicPanel添加脚本

public class DynamicPanel : MonoBehaviour {
    private Transform itemHPRoot;

    private void Start() {
        //通过代码查找到 ItemHPRoot
        itemHPRoot = GameObject.Find("Canvas/DynamicPanel/ItemHPRoot").transform;
    }

    //血条字典
    private Dictionary itemDic = new Dictionary();
    //添加血条 参数为血条的名字,要跟随物体的Transform
    public void AddItemHP(string name,Transform trans) {
        ItemHP item = null;
        if(itemDic.TryGetValue(name,out item)) {
            return;
        }
        else {
            //动态加载血条预制体
            GameObject go = Resources.Load("ItemHP");
            //实例化血条
            go = Instantiate(go);
            //给血条设置父物体
            go.transform.SetParent(itemHPRoot);
            //初始化时将血条显示在屏幕外
            go.transform.localPosition = new Vector3(-1000, 0, 0);
            ItemHP itemHp = go.GetComponent();
            //初始化血条
            itemHp.InitItemInfo(trans);
            itemDic.Add(name, itemHp);
        }
    }
    //移除血条
	public void RmvHpItem(string name) {
        ItemHP itemHp = null;
        if(itemDic.TryGetValue(name,out itemHp)) {
            Destroy(itemHp.gameObject);
            itemDic.Remove(name);
        }
    }
}

(5)在需要跟随的物体上添加对应的脚本,生成物体时就动态生成血条,当物体需要销毁时调用DynamicPanel中的RmvHpItem函数即可实现

private DynamicPanel dynamicPanel;
private void Start() {
    dynamicPanel = GameObject.Find("DynamicPanel").GetComponent();
    dynamicPanel.AddItemHP("player", transform);
}

 

你可能感兴趣的:(Unity相关)