- Home /
How do I get the AI to patrol back to his points once I am not in his vision anymore?
I am trying to create a script where the AI patrols and when you are in his field of vision he will start chasing you. As soon as you are not in his field of vision anymore he is supposed to go back to his patrol point and patrol again. So far, what the AI does is, he chases me and as soon as he stops chasing me he either goes back to one of the patrol points and stands there or moves with low speed. How do I fix this I can't seem to find a solution. Could anyone please help me out? :)
Here is the script:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI;
public class PatrolScript : MonoBehaviour {
public Transform[] path;
public float patrolSpeed = 5f;
public float reachDistance = 1f;
public int currentPoint = 0;
public GameObject target;
public float aiVision = 5f;
private NavMeshAgent myAgent;
Transform me;
void Start()
{
myAgent = GetComponent<NavMeshAgent>();
}
void Update()
{
if (Vector3.Distance(transform.position, target.transform.position) < aiVision)
{
myAgent.SetDestination(target.transform.position);
}
else
{
{
float distance = Vector3.Distance(path[currentPoint].position, transform.position);
transform.position = Vector3.MoveTowards(transform.position, path[currentPoint].position, Time.deltaTime * patrolSpeed);
if (distance <= reachDistance)
{
currentPoint++;
}
if (currentPoint >= path.Length)
{
currentPoint = 0;
}
}
}
}
void OnDrawGizmos()
{
if (path.Length > 0)
for (int i = 0; i < path.Length; i++)
{
if (path[i] != null)
{
Gizmos.DrawSphere(path[i].position, reachDistance);
}
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612113416im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
AI Movement with Rigidbody Physics? 0 Answers
AI movement in D 0 Answers