Acredito que esses são os Scripts envolvidos:
Health:using System;
using UnityEngine;
public class Health : MonoBehaviour
{
[SerializeField] private int lives;
public event Action OnDead;
public event Action OnHurt;
public void TakeDamage()
{
lives--;
HandleDamageTaken();
}
private void HandleDamageTaken()
{
if (lives <= 0)
{
OnDead?.Invoke();
}
else
{
OnHurt?.Invoke();
}
}
}
BaseEnemy:
using System.Collections;
using UnityEngine;
[RequireComponent(typeof(Animator), typeof(AudioSource))]
public abstract class BaseEnemy : MonoBehaviour
{
protected Animator _Animator;
protected AudioSource _AudioSource;
protected Health _Health;
protected bool canAttack = true;
protected virtual void Awake()
{
_Animator = GetComponent<Animator>();
_AudioSource = GetComponent<AudioSource>();
_Health = GetComponent<Health>();
_Health.OnHurt += PlayHurtAnimation;
_Health.OnDead += HandleDeath;
}
protected abstract void Update();
private void PlayHurtAnimation() => _Animator.SetTrigger("Hurt");
private void HandleDeath()
{
canAttack = false;
GetComponent<BoxCollider2D>().enabled = false;
_Animator.SetTrigger("Dead");
StartCoroutine(DestroyEnemy(2));
}
private IEnumerator DestroyEnemy(int time)
{
yield return new WaitForSeconds(time);
Destroy(this.gameObject);
}
}
MeleeEnemy:
using UnityEngine;
public class MeleeEnemy : BaseEnemy
{
[Header("Attack properties")]
[SerializeField] private Transform detectPosition;
[SerializeField] private Vector2 detectBoxSize;
[SerializeField] private LayerMask playerLayer;
[SerializeField] private float attackCooldown;
private float cooldownTimer;
protected override void Update()
{
cooldownTimer += Time.deltaTime;
VerifyCanAttack();
}
private void VerifyCanAttack()
{
if (cooldownTimer < attackCooldown || canAttack == false) return;
if (PlayerInSight())
{
_Animator.SetTrigger("Attack");
AttackPlayer();
}
}
private void AttackPlayer()
{
cooldownTimer = 0;
if (CheckPlayerInDetectArea().TryGetComponent(out Health playerHealth))
{
print("Making player take damage");
playerHealth.TakeDamage();
}
}
private Collider2D CheckPlayerInDetectArea()
{
return Physics2D.OverlapBox(detectPosition.position, detectBoxSize, 0f, playerLayer);
}
private bool PlayerInSight()
{
Collider2D playerCollider = CheckPlayerInDetectArea();
return playerCollider != null;
}
private void OnDrawGizmos()
{
if (detectPosition == null) return;
Gizmos.color = Color.red;
Gizmos.DrawWireCube(detectPosition.position, detectBoxSize);
}
}
Método do ataque do jogador:
private void Attack()
{
Collider2D[] hittedEnemies = Physics2D.OverlapCircleAll(attackPosition.position, attackRange, attackLayer);
print("Making enemy take damage");
print(hittedEnemies.Length);
foreach (Collider2D hittedEnemy in hittedEnemies)
{
print("Checking enemy");
if (hittedEnemy.TryGetComponent(out Health enemyHealth))
{
print("Getting damage");
enemyHealth.TakeDamage();
}
}
}
Tentei achar oque era mas não conseguir, Mas o código é praticamente o mesmo da aula. Por isso não entendi onde está o erro.