hi im trying to make an ai patrol an area and if it spots the player it follows, but it chases the player no matter its sight range, code attached below, thanks.
using System.Collections;
using System.Collections.Generic;
using Unity.AI.Navigation;
using UnityEngine;
using UnityEngine.AI;
public class EnemyLogic : MonoBehaviour
{
public GameObject Player;
NavMeshAgent agent;
public Transform[] waypoints;
void Start()
{
int childnum = 0;
agent = gameObject.GetComponent<NavMeshAgent>();
foreach (Transform child in GameObject.Find("Waypoints").transform)
{
childnum++;
}
waypoints = new Transform[childnum];
childnum = 0;
foreach (Transform child in GameObject.Find("Waypoints").transform)
{
waypoints[childnum] = child;
childnum++;
}
}
// Update is called once per frame
void Update()
{
Collider[] colliders = Physics.OverlapSphere(gameObject.transform.position, 25f, layerMask: LayerMask.NameToLayer("Player"));
if (colliders.Length <1)
{
foreach (Transform waypoint in waypoints)
{
agent.destination = waypoint.position;
float distance = 0;
while (!(distance > 0.1f))
{
distance = (gameObject.transform.position - waypoint.position).magnitude;
}
}
}
else
{
agent.destination = Player.transform.position;
}
}
}