So I implemented a system like if the player is near it then the enemy will follow the player else the enemy will be following a random waypoint and then wait for some sec and then move to another waypoint or chase the player if it is near
Hers my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class Enemy : MonoBehaviour
{
private Transform player;
[SerializeField] private Transform[] waypoints;
[SerializeField] private float waypointDistance = 1f;
[SerializeField] private float playerDistance = 2f;
[SerializeField] private float waitBeforeMoving;
private int currentWaypoint;
private AIPath aiPath;
private bool isCoroutineRunning;
private void Awake() {
player = FindObjectOfType<PlayerMovement>().transform;
aiPath = GetComponent<AIPath>();
}
private void Start() {
currentWaypoint = Random.Range(0, waypoints.Length);
aiPath.destination = waypoints[currentWaypoint].position;
}
private void Update() {
if (Vector2.Distance(transform.position, player.position) <= playerDistance) {
StopAllCoroutines();
aiPath.destination = player.position;
currentWaypoint = Random.Range(0, waypoints.Length);
} else if (Vector2.Distance(transform.position, waypoints[currentWaypoint].position) < waypointDistance) {
if (!isCoroutineRunning) {
StartCoroutine(GenerateNextWaypoint());
}
aiPath.destination = waypoints[currentWaypoint].position;
} else {
aiPath.destination = waypoints[currentWaypoint].position;
}
}
IEnumerator GenerateNextWaypoint() {
Debug.Log("Coroutine started");
isCoroutineRunning= true;
yield return new WaitForSeconds(waitBeforeMoving);
currentWaypoint = Random.Range(0, waypoints.Length);
Debug.Log("New waypoint generated");
isCoroutineRunning = false;
}
}