UGUI 人物血条制作

来源:互联网 发布:手机兼职 知乎 编辑:程序博客网 时间:2024/04/29 05:10

1.创建Image控件,修改名称为UIProgressBar,创建Image控件,作为血条


2.

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


public class test3_1 : MonoBehaviour {
    public int Percentage = 100;
    Image m_Progress;
    Image m_Bar;


    float m_proWidth;
    float m_barWidth;
    float m_barHeight;
    float m_maxBarWidth;
// Use this for initialization
void Start () {
        GameObject obj = this.gameObject;
        m_Progress = obj.GetComponent<Image>();
        m_Bar = obj.transform.Find("Bar").GetComponent<Image>();
        m_proWidth = m_Progress.rectTransform.rect.width;
        m_barWidth = m_Bar.gameObject.GetComponent<RectTransform>().sizeDelta.x;
        m_barHeight = m_Bar.gameObject.GetComponent<RectTransform>().sizeDelta.y;
        m_maxBarWidth = m_barWidth;
}

    public void SetPercentage(int _value)
    {
        Percentage = _value;
    }
// Update is called once per frame
void Update () {
if(Percentage > 100)
        {
            Percentage = 100;
        }
        else if(Percentage < 0)
        {
            Percentage = 0;
        }
        m_barWidth = m_proWidth / 100 * Percentage;
        m_Bar.gameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(m_barWidth, m_barHeight);
        float offset = m_barWidth - m_maxBarWidth;


        Debug.Log(offset + "  "+m_barWidth);
        //没有下面这句话会双向缩放
        m_Bar.gameObject.GetComponent<RectTransform>().anchoredPosition = new Vector2(offset / 2, 0);
}
}

原创粉丝点击