나만의 것으로 만들기
Coddy의 Unity 게임: 3D 스네이크 코스 레슨. 14개 중 14번째.
마지막으로 남은 기능은 게임을 닫아도 유지되는 최고 점수입니다. PlayerPrefs가 이를 저장합니다. Start()에서 기본값과 함께 읽고, 게임 오버 시 점수가 최고 점수를 넘으면 저장하세요. 레이싱 게임에서는 낮은 시간이 더 좋으므로 최고 랩 타임을 반대로 저장합니다:
if (lapTime < bestLap)
{
bestLap = lapTime;
PlayerPrefs.SetFloat("BestLap", bestLap);
}이제 게임을 원하는 대로 조정할 수 있습니다. Snake의 숫자들이 게임의 느낌을 결정합니다. tick을 0.25로 설정하면 차분하게 시작하고 0.1로 설정하면 빠르게 시작합니다. speedUp을 0.01로 설정하면 뱀의 속도가 더 빨리 올라가고, minTick을 0.05로 설정하면 게임 후반부가 더 정신없이 진행됩니다. 이 플레이어의 Inspector는 읽기 전용이고, 코스의 씬에서는 이 세 필드가 코드에 설정된 값을 그대로 사용하므로, 선언된 곳에서 값을 변경한 다음 Play를 누르세요. 자신의 Unity 프로젝트에서는 Inspector의 Snake 컴포넌트에서 값을 변경하세요. 코드에서 기본값을 새로 설정해도 씬에 이미 있는 컴포넌트에는 적용되지 않습니다.
챌린지
어려움GameManager에public TMP_Text bestText;(씬에서 이를 오른쪽 위의 BestText에 연결)와private int best;를 추가합니다.Start()에서 키BestScore를 사용해best를 불러옵니다. 저장된 값이 없으면 0을 사용하고,Best: 0으로 표시합니다.GameOver()에서score가best보다 높으면score를 최고 점수로 설정하고,BestScore에 저장한 다음 표시합니다.
Play를 누른 다음 Check를 누릅니다. 그런 다음 게임을 플레이하고, 게임이 마음에 들 때까지 tick, speedUp, minTick을 조정합니다.
직접 해보기
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public Snake snake;
public GameObject foodPrefab;
public TMP_Text scoreText;
public GameObject gameOverPanel;
public Button playAgainButton;
private Transform food;
private int score;
void Awake()
{
Instance = this;
}
void Start()
{
scoreText.text = "Score: 0";
playAgainButton.onClick.AddListener(PlayAgain);
food = Instantiate(foodPrefab).transform;
MoveFood();
}
public bool IsFood(Vector3 cell)
{
return cell == food.position;
}
public void Eat()
{
score++;
scoreText.text = "Score: " + score;
MoveFood();
}
public void GameOver()
{
gameOverPanel.SetActive(true);
}
void PlayAgain()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
void MoveFood()
{
List<Vector3> free = new List<Vector3>();
for (int x = -snake.edge; x <= snake.edge; x++)
{
for (int z = -snake.edge; z <= snake.edge; z++)
{
Vector3 cell = new Vector3(x, 0f, z);
if (!snake.Occupies(cell))
{
free.Add(cell);
}
}
}
food.position = free[Random.Range(0, free.Count)];
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.