Menu
CoddyTech

波次计数器

Coddy Unity 塔防游戏 课程的第 24 课,共 25 课。

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 在线编辑器