GameManager는 Singleton이어야 한다! 2개 이상 생성되는 일이 없도록 할 것
public static GameManager I;
void Awake()
{
I = this;
}
점수를 올려주는 함수 생성
int totalScore = 0;
public void addScore(int score)
{
totalScore += score;
}
빗방울과 르탄이가 부딪혔다는 사실을 알게 하기 위해 rtan에 tag 및 collider 추가
빗방울이 르탄이와 부딪혔을 때 빗방울의 점수를 GameManager의 addScore 함수로 넘겨주기
void OnCollisionEnter2D(Collision2D coll)
{
...
if (coll.gameObject.tag == "rtan")
{
Destroy(gameObject);
GameManager.I.addScore(score);
}
}
GameManager에 ScoreText 선언 및 업데이트 하기
using UnityEngine.UI;
public Text scoreText;
public void addScore(int score)
{
...
scoreText.text = totalScore.ToString();
}
제한시간 limit에서 시간이 흐르는 만큼 빼기
// GameManager
public Text timeText;
float limit = 60f;
void Update()
{
limit -= Time.deltaTime;
timeText.text = limit.ToString("N2"); // N2는 소수점 둘째자리까지 표시
}
시간이 다 되면 멈추게 하기
void Update()
{
limit -= Time.deltaTime;
if (limit < 0)
{
Time.timeScale = 0.0f;
limit = 0.0f;
}
timeText.text = limit.ToString("N2");
}
public GameObject panel;
void Update()
{
...
if (limit < 0)
{
Time.timeScale = 0.0f;
panel.SetActive(true);
limit = 0.0f;
}
...
}
Panel에서 Add Component -> Button
재시작 함수 만들기 -> GameManager가 할 일
using UnityEngine.SceneManagement;
public void retry()
{
SceneManager.LoadScene("MainScene");
}
panel script 생성
public void retry()
{
gameManager.I.retry();
}
Panel의 Button에서 OnClick 설정
게임 시작 시 timeScale, timeLimit, totalScore를 초기화 해줘야 한다.
// GamaManager
void Start()
{
...
initGame();
}
void initGame()
{
Time.timeScale = 1.0f;
totalScore = 0;
limit = 60.0f;
}