Unity

[Unity] 프로그래스바(ProgressBar) 만들기

usingsystem 2023. 3. 27. 17:03
728x90

UI 생성

  • Slider 생성

Slider 설명

  • Fill

Fill Area 안에 Fill의 image 색을 변경하면 위의 사진처럼 value에 따라 색상이 변경된다.

 

  • FillArea 

Fill Area의 크기를 조정하여 색상이 채워지는 부분을 조절할 수 있다.

 

  • (디테일) Hp bar처럼 오브젝트를 따라다니게 만드는 방법

해당 Slider을 그리는 cavas를 world space로 변경하고 소스에서 해당 오브젝트 포지션으로 맞춰주면 된다.


Progress Bar 소스 제어방법

Canvas에 Progress Bar를 제어하는 cs 파일을 컴포넌트 한 경우

public class ProgressBarTest : MonoBehaviour
{
    protected Dictionary<Type, UnityEngine.Object[]> _objects = new Dictionary<Type, UnityEngine.Object[]>();
    enum GameObjects
    {
        Slider,
    }
    void Start()
    {
        Bind<GameObject>(typeof(GameObjects)); //slider오브젝트를 찾아서 내부 Dictionary _objects에 저장한다.
        GetObject((int)GameObjects.Slider);//_objects에 저장한 slider를 찾아온다.
    }

    int _num = 0; // slider에 적용할 data 값.
    int AllData = 100;// slider의 max
    void Update()
    {
        SetTimerRatio(_num / (float)AllData); // slider에 데이터 적용 함수.
        _num++;
    }

    public void SetTimerRatio(float ratio)
    {
       
        GameObject go = GetObject((int)GameObjects.Slider); //slider 오브젝트를 찾아 go 변수에 객체를 할당한다.
        Slider slider = go.GetComponent<Slider>();//해당 go 오브젝트 즉 canvas가 있는 오브젝트의 slider 컴포넌트를 찾아온다.
        slider.value = ratio;//slider value를 통해 값을 적용한다.
    }

    // slider오브젝트를 찾아서 내부 Dictionary _objects에 저장한다.
    protected void Bind<T>(Type type) where T : UnityEngine.Object
    {
        string[] names = Enum.GetNames(type);
        UnityEngine.Object[] objects = new UnityEngine.Object[names.Length];
        _objects.Add(typeof(T), objects);

        for (int i = 0; i < names.Length; i++)
        {
            if (typeof(T) == typeof(GameObject))
                objects[i] = Util.FindChild(gameObject, names[i], true);
            else
                objects[i] = Util.FindChild<T>(gameObject, names[i], true);

            if (objects[i] == null)
                Debug.Log($"Failed to bind({names[i]})");
        }
    }

    //_objects에 저장한 slider를 찾아온다.
    protected GameObject GetObject(int idx) { return Get<GameObject>(idx); }
    protected T Get<T>(int idx) where T : UnityEngine.Object
    {
        UnityEngine.Object[] objects = null;
        if (_objects.TryGetValue(typeof(T), out objects) == false)
            return null;

        return objects[idx] as T;
    }
}

Slider에 Progress Bar를 제어하는 cs 파일을 컴포넌트 한 경우

public class ProgressBarTest : MonoBehaviour
{
    int _num = 0; // slider에 적용할 data 값.
    int AllData = 100;// slider의 max
    void Update()
    {
        SetTimerRatio(_num / (float)AllData); // slider에 데이터 적용 함수.
        _num++;
    }

    public void SetTimerRatio(float ratio)
    {
        Slider slider = gameObject.GetComponent<Slider>();//gameOjbect는 ProgressBarTest.cs가 컴포넌트로 있는 자기 자신을 의미한다.
                                                          //자기자신의 컴포넌트 중 slider를 가져온다.
        slider.value = ratio;//slider value를 통해 값을 적용한다.
    }

}
728x90