최고 기록
Coddy Unity 여정의 실제 게임 만들기 섹션에 포함된 레슨. 56개 중 32번째.
챌린지
중급마지막 단계: 최고 기록을 기억하세요. 이전 레슨의 모든 내용을 유지하세요. 캔버스 오른쪽 위에는 BestText가 있고, 패널에는 숨겨진 NewBestText(New best!)가 있습니다. 씬에서는 GameManager에 새 필드 두 개, public TMP_Text bestText;와 public GameObject newBestText;를 추가합니다. 최고 기록을 미터 단위의 정수로 BestRun 키에 저장하세요:
Start()에서 최고 기록을 불러오고(새 플레이어라면 0)Best: 57 m처럼 표시하세요.GameOver()에서 이번 기록의 미터 단위 정수인Mathf.FloorToInt(distance)가 최고 기록을 넘으면 새 최고 기록을 저장하고 표시한 다음,newBestText를 표시하세요. 더 짧은 기록이라면 아무것도 변경되지 않습니다.
최고 기록은 Run again을 실행하거나 게임을 종료해도 유지됩니다. Play를 누르고 최고 기록을 세운 다음 그 기록을 넘겨 보세요. 그런 다음 Check를 누르세요.
직접 해보기
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;
public enum GameState { Playing, GameOver }
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public float speed = 10f;
public float speedUp = 0.5f;
public float maxSpeed = 20f;
public TMP_Text distanceText;
public GameObject gameOverPanel;
public Button restartButton;
public GameState state = GameState.Playing;
private float distance;
void Awake()
{
Instance = this;
}
void Start()
{
restartButton.onClick.AddListener(Restart);
}
void Update()
{
if (state != GameState.Playing) return;
speed = Mathf.Min(speed + speedUp * Time.deltaTime, maxSpeed);
distance += speed * Time.deltaTime;
distanceText.text = "Distance: " + Mathf.FloorToInt(distance) + " m";
}
public void GameOver()
{
state = GameState.GameOver;
speed = 0f;
gameOverPanel.SetActive(true);
}
void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}