So, I’ve been trying to get my monster AI script to switch between patrolling and chasing; however, they try to chase and they’re stuck on the same path. Here’s the script:
// How do monsters patrol certain areas?
using UnityEngine;
[RequireComponent(typeof(NavMeshAgent2D))]
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(MonsterAI))]
public class Patrol : MonoBehaviour {
[Header("Setting the Path")]
public Transform[] points;
public Player[] players;
private int destPoint = 0;
private NavMeshAgent2D agent;
[Header("Chasing, Patrolling, or Still?")]
public string action = "Still";
[Header("Who to Chase?")]
public int target;
void Start()
{
target = Random.Range(0, players.Length);
agent = GetComponent<NavMeshAgent2D>();
/* Disabling auto-braking allows for continuous movement
between points (ie, the agent doesn't slow down as it
approaches a destination point).*/
agent.autoBraking = false;
if (action == "Patrolling")
{
agent.enabled = true;
GotoNextPoint();
}
else
{
agent.enabled = false;
Chase();
}
}
void Chase()
{
agent.destination = players[target].transform.position;
}
void GotoNextPoint() {
// Returns if no points have been set up or we're not patrolling
if (points.Length == 0 || action != "Patrolling")
return;
// Set the agent to go to the currently selected destination.
agent.destination = points[destPoint].position;
// Choose the next point in the array as the destination,
// cycling to the start if necessary.
destPoint = (destPoint + 1) % points.Length;
}
void Update () {
// Choose the next destination point when the agent gets
// close to the current one.
if (!agent.pathPending && agent.remainingDistance < 0.5f && action == "Patrolling")
GotoNextPoint();
}
}