Unity - 버튼에 조건문 추가하기

sh·2023년 12월 20일

팀프로젝트 중.
게임 정지 버튼이 게임오버가 난 상태에서도 계속 눌려지는게 확인
이 부분을 고쳐야 할 것 같아서 버튼에 조건문을 추가해주었다.

우선 Life갯수를 받는 text를 가져온 다음
int.TryParse로 적합한 형태인지 확인 && 그리고 그 값을 int형태로 받아온다

 bool CheckInt = int.TryParse(life.text, out lifeCount); 

첫번째 인자 life.text는 내가 받아오는 데이터 ( life 갯수, string 형태로 되어있음)
두번째 인자는 int로 반환한 값을 넣고 싶은 변수 (lifeCount)
out과 함께 써야 함**

그리고 return은 변환이 잘 되어있는지 확인하는 bool 값으로 나타낸다.

그래서 함수를 실행하기 전에
CheckInt가 true인지, lifeCount가 0보다 큰지 두개 모두 확인한 다음 실행하도록 만들어주었다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Menu : MonoBehaviour
{
    public Text life; 
    public GameObject MenuPanel;
    private int lifeCount;

    public void StopGame()
    {
        bool CheckInt = int.TryParse(life.text, out lifeCount); 

        Debug.Log(lifeCount);
        if (CheckInt && lifeCount > 0)
        {
      
         /*
         게임정지를 실행하는 코드.
         */

        }
    }

    public void CloseMenuPanel()
    {
        Time.timeScale = 1f;
        MenuPanel.SetActive(false);
    }

}

0개의 댓글