Unity/기능구현

[Unity] 게이지바 구현하기

민트초밥 2024. 2. 25. 22:11

목표 : 체력, 경험치 UI에 사용할 수 있는 게이지바 구현

 

 

#1. UI 구성

Image 오브젝트 생성 (Gauge로 이름 변경)

 

 

 

적당한 크기로 이미지 크기 조절

 

 

 

Image 컴포넌트의 Image Type을 Filled로 변경

(Image Type을 변경하기 위해서는 Source Image가 None 아니어야 한다.)

 

 

 

Fill Method, Fill Origin을 변경하여 사용하고자 하는 게이지의 타입을 변경한다.

(여기서는 가로로 된 게이지를 만들기 때문에 Fill Method를 Horizontal 타입으로 선택)

 

 

 

게이지의 값을 표시해 줄 Text 컴포넌트도 추가한다.

 

 

 

게이지의 변화를 확인하기 위해 색 변경 & 배경 추가

 

 

 

#2. 기능 구현

Gauge 스크립트를 생성해서 추가한다.

 

 

 

Image 컴포넌트의 fillAmout 속성 값을 변경하면 표시되는 이미지의 비율을 설정할 수 있다 (0 ~ 1)

0.5f로 설정하면 50%만큼 이미지를 표현한다.

public class Gauge : MonoBehaviour
{
    public Image gauge;
    public Text gaugeText;

    private void Start()
    {
        gauge.fillAmount = 0.5f;   
    }
}

 

 

 

fillAmount 값을 텍스트로 표현

public class Gauge : MonoBehaviour
{
    public Image gauge;
    public Text gaugeText;

    private void Start()
    {
        gauge.fillAmount = 0.5f;
        gaugeText.text = gauge.fillAmount.ToString();
    }
}

 

 

 

#3. 기능 확장

게이지를 표시하는 건 fillAmount 값만 설정하면 되지만, 조금 더 기능을 추가해 보도록 하자.

 

 

체력바 게이지처럼 특정 값을 게이지의 비율로 나타낼 수 있다.

ex. 0~1000에서 700의 비율 계산 

public class Gauge : MonoBehaviour
{
    public Image gauge;
    public Text gaugeText;

    private void Start()
    {
        SetGauge(0, 1000, 700);
    }

    public void SetGauge(int min, int max, int currentValue)
    {
        gauge.fillAmount = (currentValue - min) / (float)(max - min);
        gaugeText.text = currentValue.ToString();
    }
}

 

 

 

 

 

게이지가 0부터 시작하지 않아도 된다.

public class Gauge : MonoBehaviour
{
    public Image gauge;
    public Text gaugeText;

    private void Start()
    {
        SetGauge(1000, 2000, 1300);
    }

    public void SetGauge(int min, int max, int currentValue)
    {
        gauge.fillAmount = (currentValue - min) / (float)(max - min);
        gaugeText.text = currentValue.ToString();
    }
}

 

 

 

게이지가 서서히 채워지는 것처럼 보이게 하기

public class Gauge : MonoBehaviour
{
    public Image gauge;
    public Text gaugeText;

    private void Start()
    {
        StartCoroutine(GaugeAnimation(1000, 2000, 1000, 1300, 3f));
    }

    private IEnumerator GaugeAnimation(int min, int max, int startValue, int targetValue, float animationTime)
    {
        float elapsedTime = 0f;
        float currentValue = 0f;

        while(elapsedTime < animationTime)
        {
            currentValue = startValue + ((targetValue - startValue) * (elapsedTime / animationTime));

            gauge.fillAmount = (currentValue - min) / (max - min);
            gaugeText.text = currentValue.ToString();

            elapsedTime += Time.deltaTime;

            yield return null;
        }
    }
}

 

 

 

소수점이 표시되는게 불편해서 텍스트는 정수 값으로 변경

gaugeText.text = Mathf.RoundToInt(currentValue).ToString();

반응형