보상
Coddy의 Unity 게임: 타워 디펜스 코스 레슨. 25개 중 13번째.
타워가 쓰러뜨린 적 하나하나는 reward를 지급합니다. Enemy는 기지에 도달했을 때 알리는 방식과 마찬가지로 정적 이벤트 Killed를 통해 처치 사실을 알리고, GameManager는 이 이벤트를 수신해 돈을 추가합니다.
처치 보상은 한 번만 지급되어야 합니다. Destroy는 객체를 즉시 제거하지 않습니다. 프레임이 끝날 때 제거되며, 그때까지는 게임 안에 남아 있습니다. 같은 프레임에 두 발의 공격이 명중할 수 있으며, 두 번째 공격은 체력이 0인 채로 아직 남아 있는 적을 발견합니다. TakeDamage가 체력이 0 이하일 때마다 처치 사실을 알린다면, 두 번째 공격도 보상을 지급하게 됩니다. 다트가 나오는 풍선 게임에도 같은 문제가 생기며, bool로 이를 막을 수 있습니다:
public void Pop()
{
if (popped)
{
return;
}
popped = true;
Popped?.Invoke(this);
Destroy(gameObject);
}적에게는 추가 bool이 필요하지 않습니다. 체력만으로 이미 죽었는지 알 수 있기 때문입니다. 체력이 0 이하인 상태를 발견한 TakeDamage는 더 이상 할 일이 없습니다.
챌린지
중급적을 처치할 때마다 적의 보상을 획득합니다.
Enemy에public static event Action<Enemy> Killed;를 추가하고, 적을 파괴하기 직전에TakeDamage에서 이벤트를 발생시키세요.- 처치 보상이 한 번만 지급되도록
TakeDamage를if (health <= 0) return;로 시작하세요. GameManager에public void Earn(int amount)를 추가하고(금액을 더한 다음 표시하세요),Enemy.Killed를 구독해enemy.data.reward를 획득하게 하세요.
‘플레이’를 누르세요. 타워가 작동하면서 돈이 늘어납니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
using System;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour, IDamageable
{
public static readonly List<Enemy> All = new List<Enemy>();
public static event Action<Enemy> ReachedBase;
public EnemyData data;
public Transform[] waypoints;
private int next = 1;
private int health;
void Awake()
{
health = data.maxHealth;
}
void OnEnable()
{
All.Add(this);
}
void OnDisable()
{
All.Remove(this);
}
void Update()
{
Vector3 target = waypoints[next].position;
transform.position = Vector3.MoveTowards(transform.position, target, data.speed * Time.deltaTime);
if (transform.position == target)
{
next++;
if (next == waypoints.Length)
{
ReachedBase?.Invoke(this);
Destroy(gameObject);
}
}
}
public void TakeDamage(int amount)
{
health -= amount;
if (health <= 0)
{
Destroy(gameObject);
}
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Unity 게임: 타워 디펜스의 모든 레슨
직접 연습해 보세요: Unity 플레이그라운드