Bộ đếm làn sóng
Bài học 24 trên 25 trong khóa học Game Unity: thủ thành của Coddy.
HUD hiển thị số đợt. Bộ tạo đợt biết số này, và GameManager hiển thị nó, vì vậy bộ tạo đợt phát ra một sự kiện C#, WaveStarted, kèm theo số đợt hiện tại và tổng số đợt. Khác với các sự kiện tĩnh của kẻ địch, sự kiện này thuộc về một bộ tạo đợt duy nhất, và GameManager đăng ký nhận sự kiện thông qua trường spawner:
void OnEnable()
{
spawner.WaveStarted += ShowWave;
}Action<int, int> truyền hai số nguyên, vì vậy ShowWave nhận hai tham số: void ShowWave(int wave, int total).
Thử thách
Trung bìnhHiển thị đợt hiện tại.
- Trong
WaveSpawner, thêmpublic event Action<int, int> WaveStarted;(using System;) và phát sự kiện vớii + 1vàwaves.Countkhi một đợt bắt đầu. - Trong
GameManager, thêmspawner(WaveSpawner) vàwaveText(TMP_Text) có thuộc tính serialized. Đăng ký sự kiện trong OnEnable, hủy đăng ký trong OnDisable và hiển thịWave 1/8.
Nhấn Chơi: Wave 1/8 hiển thị ở góc trên bên phải khi đợt đầu tiên bắt đầu. Sau đó nhấn Kiểm tra.
Tự làm thử
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;
}
}
Tất cả bài học trong Game Unity: thủ thành
Tự luyện tập: Playground Unity