Don’t really see the problem in the code but still the enemy attacks the player when it is dead. if anyone can se the problem or got another solution it would be great.
namespace RPG.Characters
{
[RequireComponent(typeof(HealthSystem))]
[RequireComponent(typeof(WeaponSystem))]
public class EnemyAI : MonoBehaviour
{
[SerializeField] float chaseRadius = 6f;
[SerializeField] WaypointContainer patrolPath;
[SerializeField] float waypointTolerance = 2f;
[SerializeField] float waypointDwellTime = 2f;
PlayerControl player = null;
Character character;
int nextWaypointIndex;
float currentWeaponRange;
float distanceToPlayer;
bool isAttacking = false;
enum State { idle, patrolling, attacking, chasing }
State state = State.idle;
public WaypointContainer PatrolPath
{
get
{
return patrolPath;
}
set
{
patrolPath = value;
}
}
void Start()
{
character = GetComponent<Character>();
player = FindObjectOfType<PlayerControl>();
}
void Update()
{
distanceToPlayer = Vector3.Distance(player.transform.position, transform.position);
WeaponSystem weaponSystem = GetComponent<WeaponSystem>();
currentWeaponRange = weaponSystem.GetCurrentWeapon().GetMaxAttackRange();
if (distanceToPlayer > chaseRadius && state != State.patrolling)
{
StopAllCoroutines();
weaponSystem.StopAttacking();
StartCoroutine(Patrol());
}
if (distanceToPlayer <= chaseRadius && state != State.chasing)
{
StopAllCoroutines();
weaponSystem.StopAttacking();
StartCoroutine(ChasePlayer());
}
if (distanceToPlayer <= currentWeaponRange && state != State.attacking)
{
StopAllCoroutines();
weaponSystem.AttackTarget(player.gameObject);
}
}
IEnumerator Patrol()
{
state = State.patrolling;
while (PatrolPath != null)
{
Vector3 nextWaypointsPos = PatrolPath.transform.GetChild(nextWaypointIndex).position;
character.SetDestination(nextWaypointsPos);
CycleWaypointWhenClose(nextWaypointsPos);
yield return new WaitForSeconds(waypointDwellTime);
}
}
private void CycleWaypointWhenClose(Vector3 nextWaypointsPos)
{
if (Vector3.Distance(transform.position, nextWaypointsPos) <= waypointTolerance)
{
nextWaypointIndex = (nextWaypointIndex + 1) % PatrolPath.transform.childCount;
}
}
IEnumerator ChasePlayer()
{
state = State.chasing;
while (distanceToPlayer >= currentWeaponRange)
{
character.SetDestination(player.transform.position);
yield return new WaitForEndOfFrame();
}
}