점수와 생명
Coddy의 Unity 게임: 벽돌깨기 코스 레슨. 16개 중 9번째.
점수와 목숨은 화면에 표시되어야 합니다. 이제 씬에는 상단에 두 개의 TextMeshPro 텍스트인 ScoreText와 LivesText가 있는 Canvas가 있고, GameManager는 TMPro 네임스페이스의 TMP_Text 필드에 이 텍스트들을 보관합니다.
숫자는 GameManager의 필드에 저장되고, 텍스트는 그 숫자를 보여 주기만 합니다. 한 메서드가 필드의 값으로 두 텍스트를 모두 다시 쓰며, 숫자를 변경하는 모든 메서드가 이 메서드를 호출합니다. Start()도 호출하므로 첫 프레임에 실제 값이 표시됩니다. 상점의 코인 카운터는 다음과 같습니다.
public TMP_Text coinsText;
int coins;
public void AddCoins(int amount)
{
coins += amount;
ShowCoins();
}
void ShowCoins()
{
coinsText.text = "Coins: " + coins;
}숫자가 바뀔 때만 텍스트가 바뀝니다. 매 Update()마다 텍스트를 다시 써도 똑같이 보이겠지만, 아무런 이유 없이 매 프레임 새 문자열을 만들게 됩니다.
챌린지
중급GameManager에using TMPro;를 추가하고,public TMP_Text scoreText와public TMP_Text livesText를 추가합니다. 씬에서 ScoreText와 LivesText를 연결합니다.void ShowHud()를 작성합니다. 현재 숫자와 함께scoreText에는Score: 0이 표시되고livesText에는Lives: 3이 표시됩니다.Start()의 끝에서, 그리고 점수나 생명 수가 바뀐 후에ShowHud()를 호출합니다.
Play를 누르고, 벽돌을 부수고, 공을 잃은 다음 Check를 누릅니다.
직접 해보기
using UnityEngine;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public Brick brickPrefab;
public Transform wall;
public int rows = 5;
public int columns = 9;
public float spacingX = 1.75f;
public float spacingY = 0.75f;
public float topY = 6f;
public int[] rowHits = { 2, 1, 1, 1, 1 };
public int lives = 3;
int score;
void Awake()
{
Instance = this;
}
void Start()
{
BuildWall();
}
void BuildWall()
{
float left = -(columns - 1) * spacingX / 2f;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
Vector3 pos = new Vector3(left + col * spacingX, topY - row * spacingY, 0f);
Brick brick = Instantiate(brickPrefab, pos, Quaternion.identity, wall);
brick.SetHits(rowHits[row]);
}
}
}
public void BrickBroken(Brick brick)
{
score += brick.points;
}
public void BallLost(Ball lost)
{
lives--;
lost.ResetToPaddle();
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.