본문 바로가기

Unity3D/C#

Unity 체력바 fillAmount로 구현 in Script

반응형

Guage Bar

 

 

웬만한 게임에서 게이지바는 쉽게 볼 수 있는데요. RPG 게임이라면 체력이나 스태미나, 또는 쿨타임, 경험치 등에서 쉽게 볼 수 있습니다. 일반적으로는 달성률을 표시할 때 많이 사용합니다. 체력, 스태미나, 쿨타임, 경험치, 달성률, 등 게이지바를 사용하는 것들은 모두 공통적으로 현재 값과 최댓값을 가지고 있습니다. 현재 값과 최댓값은 텍스트로도 표시하고 한눈에 보기 좋게 UI 적으로도 표시를 합니다. Unity에서 기본적으로 제공하는 UI 중 Image는 fillAmount라는 기능을 사용할 수 있습니다. fillAmount는 0~1의 값을 가지고 있으며 그 사이의 값을 이용해서 비율대로 이미지가 표시됩니다. 0이면 아무것도 보이지 않고 1이면 100% 다 보이게 되는 방식입니다. fillAmount는 0~1 사이의 float 값을 넣어주기만 하면 돼서 조작하기 매우 쉽습니다. fillAmount는 0~1의 사이 값이기 때문에, 게이지의 현재 값(0~최댓값)에서 최댓값을 나눠주기만 하면 됩니다.

 

 

C# (UNITY 3D)

 

 

 

이번 예시는 체력바 예시입니다. Kill 버튼을 눌러서 체력을 0으로 만들거나 Reset 버튼을 눌러 체력을 초기화할 수 있습니다. +20, -20 버튼으로 체력을 조절할 수 있습니다. Get 버튼을 누르면 현재 체력을 가져와서 표시합니다.

 

 

 

using UnityEngine.UI;

 

Image, Text를 사용하려면 UnityEngine.UI가 필요합니다.

 

 

할당

 

각 사용할 버튼, 표시할 텍스트, 게이지 바로 사용할 이미지를 사용할 스크립트에 할당해 줍니다.

 

 

 

Image 준비

 

Source Image에 반드시 Sprite를 넣어줘야 Image Tpye을 사용하여 fillAmount를 사용할 수 있습니다. 원하는 이미지를 넣어서 게이지 바를 표시하고 만약 기본적인 네모 형태를 원하시면 아래 작은 이미지를 다운받아서 넣으시면 됩니다.

스크립트에 Image Type, Fill Metho, FillOrigin을 설정 해주는 코드가 들어있지만 수동으로 하고 싶은 분들은 여기에서 하시면 됩니다.

 

작은 하얀 박스▼

 

box_white.jpg
0.01MB

 

 

 

 


    public Text message;
    public Text result; 
    public Image img; 
    public Button button_get;
    public Button button_kill;
    public Button button_reset;
    public Button button_plus;
    public Button button_minus;

    private float hp;
    private float hp_max = 100;
    private float hp_delta = 20;
    private bool isDead;

        

    void Start()
    {

        Init_HP();
        SetFunction_UI(); 
    }

    //CodeFinder
    //From https://codefinder.janndk.com/
    private void Init_HP()
    {
        Function_Button_Reset();
    }

    private void ResetFunction_UI()
    {
        button_get.onClick.RemoveAllListeners();
        button_kill.onClick.RemoveAllListeners();
        button_reset.onClick.RemoveAllListeners();
        button_plus.onClick.RemoveAllListeners();
        button_minus.onClick.RemoveAllListeners();

        //Fill Amount Type
        img.type = Image.Type.Filled;
        img.fillMethod = Image.FillMethod.Horizontal;
        img.fillOrigin = (int)Image.OriginHorizontal.Left;
    }

    private void SetFunction_UI()
    {
        //Reset
        ResetFunction_UI();
        button_get.onClick.AddListener(Function_Button_Get);
        button_kill.onClick.AddListener(Function_Button_Kill);
        button_reset.onClick.AddListener(Function_Button_Reset);
        button_plus.onClick.AddListener(Function_Button_Plus);
        button_minus.onClick.AddListener(Function_Button_Minus);
    }
    
    private void Function_Button_Get()
    {
        string txt = string.Format("{0}/{1}", hp, hp_max);
        result.text = hp.ToString(); 
        Debug.LogError("Get Current HP!\n" + txt);
    }
    private void Function_Button_Kill()
    {
        Set_HP(0);
    }
    private void Function_Button_Reset()
    {
        Set_HP(hp_max);
    }
    private void Function_Button_Plus()
    {
        Change_HP(hp_delta);
    }
    private void Function_Button_Minus()
    {
        Change_HP(-hp_delta);
    }


    private void Change_HP(float _value)
    {
        hp += _value;
        Set_HP(hp);
    }

    private void Set_HP(float _value)
    {
        hp = _value;

        string txt = "";
        if(hp<=0)
        {
            hp = 0;
            txt = "Dead";
        }
        else
        {
            if (hp > hp_max)
                hp = hp_max;
            txt = string.Format("{0}/{1}", hp, hp_max);
        }
        img.fillAmount = hp / hp_max;
        isDead = hp.Equals(0);

        message.text = txt;
        Debug.LogError("Current HP!\n" + txt);
    }
   

 

변수(variable)
message : 체력이 변경됐을 때 표시(Text)
result  : Get 버튼을 눌렀을 때 현재 체력을 표시(Text)
img : fillAmount를 사용할 이미지 (Image)
button_get : Function_Button_Get 실행(Button)
button_kill : Function_Button_Kill 실행 (Button)
button_reset : Function_Button_Reset 실행 (Button)
button_plus : Function_Button_Plus 실행 (Button)
button_minus : Function_Button_Minus 실행 (Button)

hp : 현재 체력 (float)
hp_max : 최대 체력 (float)
hp_delta : 체력 변화 값 (float)
isDead : 캐릭터가 죽었는지 (bool)

 

함수(function)
Init_HP : HP의 값과 UI 표시 초기화
ResetFunction_UI : 버튼 기능 전체 삭제, 이미지 타입 설정, fillAmount 관련 설정
SetFunction_UI  : 버튼 기능 초기화해주는 함수 실행하고 각 버튼들 기능 할당
Function_Button_Get : 현재 hp 값을 가져옴
Function_Button_Kill : 체력을 0으로 변경
Function_Button_Reset : 체력을 초기 상태로 변경
Function_Button_Plus : 체력을 delta 값만큼 증가
Function_Button_Minus : 체력을 delta 값만큼 감소
Change_HP : hp에서 매개 변수로 받은 float 값을 더함
Set_HP : hp를 매개변수로 받은 float 값으로 변경

 

 

 

Unity3D / UI / Image / fillAmount / Set HP / Change HP / Image Type / Filled / FillMethod / Horiziontal / FillOrigin / OriginHoriziontal / Left

 

 

 

반응형