본문 바로가기
개발/C#

유니티 C# 방치형 돈 자동생산 코드 작성하기 간단 구현

by SPNK 2024. 3. 14.
반응형

코드 작성

using UnityEngine;
using UnityEngine.UI;

public class MoneyManager : MonoBehaviour
{
    public float initialProductionTime = 5f; // 초기 생산 시간
    public float moneyPerSecond = 10f; // 초당 생산되는 돈
    public float moneyCostToSpeedUp = 50f; // 생산 시간을 줄이는 데 필요한 돈
    public Image progressImage; // 진행 이미지
    public Button speedUpButton; // 생산 시간을 줄이는 버튼

    private float currentProductionTime; // 현재 생산 시간
    private float currentMoney = 0f; // 현재 소지한 돈
    private Coroutine productionCoroutine; // 생산 코루틴 참조

    void Start()
    {
        // 초기 생산 시간 설정
        currentProductionTime = initialProductionTime;

        // 버튼 리스너 등록
        speedUpButton.onClick.AddListener(SpeedUpProduction);

        // 코루틴 시작: 주기적으로 돈을 생산
        productionCoroutine = StartCoroutine(ProductionCoroutine());
    }

    void Update()
    {
        // 버튼 활성화 여부 업데이트
        speedUpButton.interactable = currentMoney >= moneyCostToSpeedUp && currentProductionTime > 1f;
    }

    IEnumerator ProductionCoroutine()
    {
        while (true)
        {
            // 현재 소지한 돈 업데이트
            currentMoney += moneyPerSecond * Time.deltaTime;

            // 진행 이미지 fillAmount 업데이트
            UpdateProgress();

            yield return null;
        }
    }

    void UpdateProgress()
    {
        // 진행 이미지 fillAmount 값을 업데이트하여 진행 상태를 표시
        float progress = currentMoney / moneyCostToSpeedUp;
        progressImage.fillAmount = Mathf.Clamp01(progress);
    }

    void SpeedUpProduction()
    {
        // 돈을 사용하여 생산 시간을 줄이는 함수
        if (currentMoney >= moneyCostToSpeedUp && currentProductionTime > 1f)
        {
            currentMoney -= moneyCostToSpeedUp;
            currentProductionTime -= 1f; // 생산 시간을 1초 감소
        }
    }
}
반응형

댓글