본문 바로가기
유니티 공부/Unity

Unity - 구매, 판매 기능 구현해보기

by 코딩하는 돼징 2023. 7. 17.
반응형

기본적인 구매, 판매 기능 구현해보기

구매 기능을 더해서 상점을 만들 수 있고 판매 기능을 더해서 인벤토리에 있는 아이템들을 판매하는 기능을 구현할 수 있다.


1. 기본 세팅

01 money 값

money를 static으로 선언하여 인스턴스 없이 클래스 이름과 함께 접근할 수 있다. 이를 통해 어디서나 동일한 money 값을  사용할 수 있다.

public static int money { get; private set; }

02 Spend

static메서드로 선언해서 정적 변수에 직접 접근 가능하다. 그래서 메서드 안에서 인스턴스 생성 없이 money를 직접 접근할 수 있다.

public static void Spend(int cost)
{
    if (cost > money)
    {
        Debug.LogError("You have not enough money");
        return;
    }
    money -= cost;
}

03 Earn

public static void Earn(int income)
{
    money += income;
}

2. money값 렌더링

01 uiManager에 money값 렌더링하는 메시드 만들기

uiManager.cs

public TMP_Text money_text;

public void RenderMoney()
{
    money_text.text = controlMoney.money.ToString();
}

02 Earn,Spend 메서드에 추가

public static void Spend(int cost)
{
    if (cost > money)
    {
        Debug.LogError("You have not enough money");
        return;
    }
    money -= cost;
    uiManager.Instance.RenderMoney();
}

public static void Earn(int income)
{
    money += income;
    uiManager.Instance.RenderMoney();
}

3. 버튼에 메서드 할당하기

01 Sell 버튼

public void EarnMoney()
{
    controlMoney.earn(10);
}

02 Buy 버튼

public void SpendMoney()
{
    controlMoney.spend(10);
}

4. 결과 영상 확인하기

 

반응형

댓글