Unity's simple health bar production (UnityEngine.UI.Slider)

  1. Before starting, make a prefab of the Slider health bar.

  1. Create a new canvas. Then create UI->slider bar and place the slider bar in this canvas. This canvas will be used to make the prefab later.

  1. Delete the Background and Handle Slider Area.

  1. Select Fill in the picture above. In the inspector, select the blood bar picture as the source image, select Filled as the image type, fill the method horizontally, and maintain the aspect ratio.

  1. Make it a prefab and place it under the Resources folder

2. Place the following codes appropriately in your c# script

Transform canvasTransform;
UnityEngine.UI.Slider Slider;
    private void Start()
    {
        //血条
        //指定父级this.transform为预想指定的(一般是小怪物)物体
        canvasTransform = Instantiate(Resources.Load<GameObject>("Canvas3D"), Vector3.zero, Camera.main.transform.rotation, this.transform).transform;
        //设置当前相对于怪物的位置
        canvasTransform.localPosition = new Vector3(0,2.0f,0);
        //设置缩放
        canvasTransform.localScale = new Vector3(0.02f, 0.02f, 0.02f);
        //获取Slider组件
        Slider = canvasTransform.GetComponentInChildren<UnityEngine.UI.Slider>();
        //使用协程
        StartCoroutine(UpdataLifebar());
        
    }
    IEnumerator UpdataLifebar()
    {
        //Slider值为0-1之间
        Slider.value = (float)m_life/(float)m_maxLife;
        //设置欧拉角
        canvasTransform.transform.eulerAngles = Camera.main.transform.eulerAngles;
        yield return 0;
        //刷新
        StartCoroutine(UpdataLifebar());
    }

Guess you like

Origin blog.csdn.net/HeDanTou_/article/details/129468205