After completing the lecture, I am getting the following error when the player gets into range of an enemy:
The enemy doesn’t even try to move towards the player. Once the player is out of range of the enemy, the errors stop.
Below is my code for the AIController and Fighter script:
using UnityEngine;
using RPG.Combat;
namespace RPG.Control
{
public class AIController : MonoBehaviour
{
[SerializeField] float chaseDistance = 5f;
Fighter fighter;
GameObject player;
private void Start()
{
fighter = GetComponent<Fighter>();
player = GameObject.FindWithTag("Player");
}
private void Update()
{
if (InAttackRangeOfPlayer() && fighter.CanAttack(player))
{
fighter.Attack(player);
}
else
{
fighter.Cancel();
}
}
private bool InAttackRangeOfPlayer()
{
float distanceToPlayer = Vector3.Distance(player.transform.position, transform.position);
return distanceToPlayer < chaseDistance;
}
}
}
using UnityEngine;
using RPG.Movement;
using RPG.Core;
namespace RPG.Combat
{
public class Fighter : MonoBehaviour, IAction
{
[SerializeField] float weaponRange = 2f;
[SerializeField] float timeBetweenAttacks = 1f;
[SerializeField] float weaponDamage = 10f;
Health target;
float timeSinceLastAttack = 0f;
private void Update()
{
timeSinceLastAttack += Time.deltaTime;
if(target == null)
{
return;
}
if (target.IsDead())
{
return;
}
if (!GetIsInRange())
{
GetComponent<Mover>().MoveTo(target.transform.position);
}
else
{
GetComponent<Mover>().Cancel();
AttackBehaviour();
}
}
private void AttackBehaviour()
{
transform.LookAt(target.transform);
if(timeSinceLastAttack > timeBetweenAttacks)
{
// This will trigger the Hit() event.
TriggerAttack();
timeSinceLastAttack = 0f;
}
}
private void TriggerAttack()
{
GetComponent<Animator>().ResetTrigger("stopAttack");
GetComponent<Animator>().SetTrigger("attack");
}
//Animation Event
void Hit()
{
if(target == null)
{
return;
}
target.TakeDamage(weaponDamage);
}
private bool GetIsInRange()
{
return Vector3.Distance(transform.position, target.transform.position) < weaponRange;
}
public bool CanAttack(GameObject combatTarget)
{
if(combatTarget == null)
{
return false;
}
Health targetToTest = combatTarget.GetComponent<Health>();
return targetToTest != null && !targetToTest.IsDead();
}
public void Attack(GameObject combatTarget)
{
GetComponent<ActionScheduler>().StartAction(this);
target = combatTarget.GetComponent<Health>();
}
public void Cancel()
{
StopAttack();
target = null;
}
private void StopAttack()
{
GetComponent<Animator>().ResetTrigger("attack");
GetComponent<Animator>().SetTrigger("stopAttack");
}
}
}
The “Player” tag has also been applied to player:
Any help would be much appreciated.