Enemy AI follow player only when close

My enemy senses the player when near using my code and when the game starts I remove the player as the target from the AIDestinationSetter target. I add it back when the player gets close once again. Then the pathfinding does not happen even when I add it back.

Why is this? Is there any other way to prevent the AI from always running towards the player?

My enemy Ai code is below.

using UnityEngine;

using SensorToolkit;

using Pathfinding;

public class EnemyAI : MonoBehaviour


    #region Private Fields

    [SerializeField] private RangeSensor sensor;

    [SerializeField] private Animator animator;

    [SerializeField] private GameObject home;

    [SerializeField] private AIDestinationSetter AIDestSet;

    [SerializeField] private float turnSpeed;

    private bool targetSet = true;

    private int animIDPlayerDetected;

    private int animIDInBase;

    private GameObject detected;

    private Vector3 lookDirection;

    private Vector3 noY  = new Vector3(1, 0, 1);


    void Start()


        animIDPlayerDetected = Animator.StringToHash("detected");

        animIDInBase = Animator.StringToHash("inBase");

        animator.SetBool(animIDInBase, true);


    void Update()


        detected = sensor.GetNearest();

        if(detected != null && targetSet == false)


            //Chase(detected.gameObject, true);

            Debug.Log("player detected");

            AIDestSet.target = gameObject.transform;

            targetSet = true;


        else if(detected == null && targetSet == true)


            AIDestSet.target = null;

            targetSet = false;

            if (GetDistance() < 2f)








                Chase(home, true);


            Debug.Log("player NOT detected");



    private void Chase(GameObject target, bool plDetected)


        animator.SetBool(animIDPlayerDetected, plDetected);



    void TurnToTarget(GameObject target)


        //target.transform.position = new Vector3(target.transform.position.x, 0, target.transform.position.z);

        //transform.position = new Vector3(transform.position.x, 0, transform.position.z);

        lookDirection = (target.transform.position - transform.position).normalized;

        lookDirection = new Vector3(lookDirection.x, 0, lookDirection.z);

        transform.forward = Vector3.Lerp(transform.forward, lookDirection, Time.deltaTime * turnSpeed);


    private void Idle()


        animator.SetBool(animIDPlayerDetected, false);


    private float GetDistance()


        return (Vector3.Distance(home.transform.position, transform.position));



I managed to solve this specific problem by using the canMove flag which may not be the most efficient way as the pathfinding still goes on.

1 Like