Menu
CoddyTech

웨이브 카운터

Coddy의 Unity 게임: 타워 디펜스 코스 레슨. 25개 중 24번째.

HUD에는 웨이브 번호가 표시됩니다. 스포너는 웨이브 번호를 알고 있고 GameManager가 이를 표시하므로, 스포너는 웨이브와 전체 웨이브 수를 전달하는 C# 이벤트 WaveStarted를 발생시킵니다. 적의 정적 이벤트와 달리 이 이벤트는 하나의 스포너에 속하며, GameManager는 spawner 필드를 통해 이벤트를 구독합니다.

void OnEnable()
{
    spawner.WaveStarted += ShowWave;
}

Action<int, int>은 int 두 개를 전달하므로 ShowWave는 두 개를 받습니다. 즉, void ShowWave(int wave, int total)입니다.

challenge icon

챌린지

중급

현재 웨이브를 표시하세요.

  1. WaveSpawner에서 public event Action<int, int> WaveStarted; (using System;)를 추가하고 웨이브가 시작될 때 i + 1과 waves.Count를 사용해 이벤트를 발생시키세요.
  2. GameManager에서 직렬화된 spawner(WaveSpawner)와 waveText(TMP_Text)를 추가하세요. OnEnable에서 구독하고 OnDisable에서 구독을 해제한 다음 Wave 1/8을 표시하세요.

‘플레이’를 누르세요. 첫 번째 웨이브가 시작되면 오른쪽 상단에 Wave 1/8이 표시됩니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

using UnityEngine;
using TMPro;

public class GameManager : MonoBehaviour
{
    [SerializeField] private int startMoney = 150;
    [SerializeField] private int startLives = 20;
    [SerializeField] private TMP_Text moneyText;
    [SerializeField] private TMP_Text livesText;

    private int money;
    private int lives;

    void OnEnable()
    {
        Enemy.ReachedBase += OnReachedBase;
        Enemy.Killed += OnKilled;
    }

    void OnDisable()
    {
        Enemy.ReachedBase -= OnReachedBase;
        Enemy.Killed -= OnKilled;
    }

    void Start()
    {
        money = startMoney;
        lives = startLives;
        ShowMoney();
        ShowLives();
    }

    public bool TrySpend(int amount)
    {
        if (amount > money)
        {
            return false;
        }

        money -= amount;
        ShowMoney();
        return true;
    }

    public void Earn(int amount)
    {
        money += amount;
        ShowMoney();
    }

    void OnKilled(Enemy enemy)
    {
        Earn(enemy.data.reward);
    }

    void OnReachedBase(Enemy enemy)
    {
        lives -= enemy.data.damage;
        ShowLives();
    }

    void ShowMoney()
    {
        moneyText.text = "Money: " + money;
    }

    void ShowLives()
    {
        livesText.text = "Lives: " + lives;
    }
}

Unity 게임: 타워 디펜스의 모든 레슨

직접 연습해 보세요: Unity 플레이그라운드