최고 점수
Coddy Unity 여정의 실제 게임 만들기 섹션에 포함된 레슨. 60개 중 24번째.
최고 점수는 플레이한 모든 게임 중 가장 좋은 결과이므로 PlayerPrefs에 저장되며, 게임 점수가 최고 기록을 넘어설 때만 바뀝니다. 이 핀볼 테이블은 마지막 공이 빠져나갈 때 이를 확인합니다:
void GameOver()
{
int best = PlayerPrefs.GetInt("PinballBest", 0);
if (score > best)
{
PlayerPrefs.SetInt("PinballBest", score);
PlayerPrefs.Save();
Debug.Log("New high score: " + score);
}
}최고 점수를 결정하는 것은 비교입니다. 비교가 없으면 최고 점수가 5000점인 상태에서 300점을 얻은 게임이 300점을 저장하고 기록은 사라집니다. 저장된 최고 점수와 비교해야 합니다. 매 게임마다 0부터 시작하는 값과 비교하면 안 됩니다. 불러온 적이 없는 필드는 재시작할 때마다 0이 되므로 어떤 점수든 그 값을 넘기 때문입니다. score > best는 동점일 때 기존 기록을 유지하지만, score >= best는 동점을 새 최고 점수로 처리합니다.
플레이 중에 최고 점수를 표시하려면 Start()에서 필드에 최고 점수를 불러온 다음 그 필드를 표시하세요. 게임 점수가 최고 기록을 넘으면 필드와 PlayerPrefs, 텍스트를 함께 업데이트해야 화면과 저장된 값이 서로 달라지지 않습니다.
챌린지
중급최고 점수를 BestPoints 키에 저장하세요.
Start()에서ShowBest();위에best = PlayerPrefs.GetInt("BestPoints", 0);를 작성하세요.EndRound()의if (points > best)안에서best = points;로 설정하고,PlayerPrefs.SetInt와PlayerPrefs.Save()로 저장한 다음ShowBest();와newBestText.SetActive(true);를 호출하세요.
‘플레이’를 눌러 풍선을 펌프질하고(Space를 누르고 있다가 놓으세요), 그런 다음 정지를 누르고 다시 ‘플레이’를 누르세요. 최고 점수가 유지됩니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
using UnityEngine;
using TMPro;
public class BalloonPump : MonoBehaviour
{
public TMP_Text pointsText;
public TMP_Text bestText;
public GameObject newBestText;
public float pumpRate = 20f;
private float air;
private int points;
private int best;
private bool roundOver;
void Start()
{
ShowBest();
}
void Update()
{
if (roundOver) return;
if (Input.GetKey(KeyCode.Space))
{
air += pumpRate * Time.deltaTime;
transform.localScale = Vector3.one * (1f + air / 50f);
pointsText.text = "Points: " + Mathf.FloorToInt(air);
if (air > 100f)
{
points = 0;
pointsText.text = "Pop! Points: 0";
GetComponent<Renderer>().enabled = false;
roundOver = true;
EndRound();
}
}
else if (Input.GetKeyUp(KeyCode.Space))
{
points = Mathf.FloorToInt(air);
pointsText.text = "Points: " + points;
roundOver = true;
EndRound();
}
}
void EndRound()
{
// 여기서 새로운 최고 기록을 저장하세요
}
void ShowBest()
{
bestText.text = "Best: " + best;
}
}
실제 게임 만들기의 모든 레슨
직접 연습해 보세요: Unity 플레이그라운드