마지막 공이 중요해
Coddy의 Unity 게임: 벽돌 깨기 코스 레슨. 19개 중 18번째.
공이 세 개 플레이 중일 때는 마지막 공일 때만 공을 잃으면 생명을 잃어야 합니다. 그전까지는 공이 목록에서 제거되고 파괴됩니다. 분열하는 슬라임도 같은 방식으로 처리합니다.
public void SlimeDied(Slime slime)
{
slimes.Remove(slime);
Destroy(slime.gameObject);
if (slimes.Count == 0) Debug.Log("Room cleared");
}복제된 공이 계속 날아가는 동안 원래 공을 잃을 수도 있으므로, 목록의 첫 번째 공은 복제본일 수 있습니다. 레벨 클리어처럼 "공"이 필요한 코드는 씬의 Ball 필드가 아니라 balls[0]을 사용합니다.
챌린지
어려움추가 공을 잃어도 생명은 줄어들지 않습니다.
BallLost의 맨 앞에서:balls.Count > 1이면balls.Remove(lost);를 실행하고, 해당 객체를 파괴한 다음 반환합니다.- 레벨을 클리어하면
ball.ResetToPaddle()대신balls[0].ResetToPaddle()을 호출합니다.
‘플레이’를 누르고, 공을 분리한 다음 두 개를 놓쳐 보세요. 마지막 공이 떨어질 때까지 생명은 그대로 유지됩니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
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)
{
ball.ResetToPaddle();
BuildLevel((level + 1) % levels.Length);
}
}
public void BallLost(Ball lost)
{
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;
}
}
Unity 게임: 벽돌 깨기의 모든 레슨
직접 연습해 보세요: Unity 플레이그라운드