나만의 것으로 만들기
Coddy의 Unity 게임: 벽돌깨기 코스 레슨. 16개 중 16번째.
마지막 기능은 게임 간에 유지되는 최고 점수입니다. PlayerPrefs는 플레이어의 기기에 작은 값을 저장합니다. PlayerPrefs.GetInt(key, 0)는 값을 읽으며, 아직 저장된 값이 없으면 0을 반환하고, PlayerPrefs.SetInt(key, value)는 값을 저장합니다. 게임이 시작될 때 최고 점수를 불러오고, 게임이 끝날 때 점수가 더 높으면 저장하세요. 다시 플레이를 누르면 씬을 다시 불러오고, 새 GameManager가 최고 점수를 다시 불러옵니다.
이제 게임을 원하는 대로 조정하면 됩니다. 게임의 동작을 설정하는 모든 숫자는 코드에 초기값이 지정된 필드입니다.
Ball:speed(9) 및minVertical(0.3).Paddle:speed(14),wideFactor(1.6) 및wideSeconds(8).GameManager:lives(3),dropChance(0.15), 그리고 벽돌 간격.
레이아웃은 Inspector에 있는 GameManager의 levels 목록입니다. 숫자는 해당 횟수만큼 맞아야 하는 벽돌이고, 점은 빈칸이며, /는 다음 행의 시작을 나타냅니다. 예를 들면 1.3.1/22222입니다. 자신의 Unity 프로젝트에서는 Inspector에서 값을 변경하세요. 스크립트를 오브젝트에 추가하면 Inspector가 자체 사본을 유지하므로, 코드의 새 초기값은 더 이상 해당 오브젝트에 적용되지 않습니다.
챌린지
어려움GameManager에서public TMP_Text bestText를 추가하고(씬에서 BestText에 연결)int best를 추가합니다.Start()에서 PlayerPrefs의BestScore키에 저장된 값을 불러와best에 설정하고, 저장된 값이 없으면 0으로 설정합니다.ShowHud()에서도 최고 점수를bestText에Best: 0형식으로 표시합니다.- 게임이 끝났을 때 점수가
best보다 높으면, 해당 점수를best에 저장하고BestScore키로 저장한 다음 표시합니다.
그런 다음 게임을 원하는 대로 바꿔 보세요. 속도와 생명 수, 드롭 확률, 파워업의 효과를 조정하고 원하는 느낌이 들 때까지 플레이하세요.
Play를 누르고 최고 점수를 세운 다음 Check를 누르세요.
직접 해보기
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public Brick brickPrefab;
public Transform wall;
public string[] levels;
public float spacingX = 1.75f;
public float spacingY = 0.75f;
public float topY = 6f;
public Ball ball;
public int lives = 3;
public TMP_Text scoreText;
public TMP_Text livesText;
public GameObject gameOverPanel;
public GameObject[] powerUps;
public float dropChance = 0.15f;
int score;
int level;
int bricksLeft;
List<Ball> balls = new List<Ball>();
void Awake()
{
Instance = this;
}
void Start()
{
balls.Add(ball);
BuildLevel(0);
ShowHud();
}
void BuildLevel(int index)
{
level = index;
string[] rows = levels[index].Split('/');
for (int row = 0; row < rows.Length; row++)
{
string line = rows[row];
float left = -(line.Length - 1) * spacingX / 2f;
for (int col = 0; col < line.Length; col++)
{
char c = line[col];
if (c == '.') continue;
Vector3 pos = new Vector3(left + col * spacingX, topY - row * spacingY, 0f);
Brick brick = Instantiate(brickPrefab, pos, Quaternion.identity, wall);
brick.SetHits(c - '0');
bricksLeft++;
}
}
}
public void BrickBroken(Brick brick)
{
score += brick.points;
bricksLeft--;
ShowHud();
if (Random.value < dropChance)
{
GameObject prefab = powerUps[Random.Range(0, powerUps.Length)];
Instantiate(prefab, brick.transform.position, Quaternion.identity);
}
if (bricksLeft == 0)
{
balls[0].ResetToPaddle();
BuildLevel((level + 1) % levels.Length);
}
}
public void BallLost(Ball lost)
{
if (balls.Count > 1)
{
balls.Remove(lost);
Destroy(lost.gameObject);
return;
}
lives--;
ShowHud();
if (lives == 0)
{
gameOverPanel.SetActive(true);
lost.gameObject.SetActive(false);
}
else lost.ResetToPaddle();
}
public void SplitBall()
{
Ball source = balls[0];
Ball left = Instantiate(source, source.transform.position, Quaternion.identity);
left.Launch(new Vector3(-0.6f, 1f, 0f));
balls.Add(left);
Ball right = Instantiate(source, source.transform.position, Quaternion.identity);
right.Launch(new Vector3(0.6f, 1f, 0f));
balls.Add(right);
}
public void PlayAgain()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
void ShowHud()
{
scoreText.text = "Score: " + score;
livesText.text = "Lives: " + lives;
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.