Enemy should follow the Player if he is in range, but how?

Hello Together,
hope someone can help me. I just want that the enemy starting to follow the player if he is in range.

I have this script on my enemy and he following the Playercontroller:

I would be so happy if someone can help me

public class EnemyController1 : MonoBehaviour
{
    Animator animator;
    public float minSpeed = 3f;
    public float maxSpeed = 4;
    public AudioClip deathAudio;
    public Transform target;
    private NavMeshAgent agent;
    private Rigidbody[] rbs;

    // Start is called before the first frame update
    void Start()
    {
        rbs = GetComponentsInChildren<Rigidbody>();
        agent = GetComponent<NavMeshAgent>();
        target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
        GetComponent<Animator>().speed = Random.Range(minSpeed, maxSpeed);
        DisactivateZombie();
    }

    void Update()
    {
        agent.SetDestination(target.position);

        if (Vector3.Distance(target.position, transform.position) < 1.5f)
            UnityEngine.SceneManagement.SceneManager.LoadScene(0)
    }

    
    private void OnCollisionEnter(Collision collision)
    {
        if (collision.transform.tag == "Weapon")
        {
         
            Destroy(gameObject);
            scoreCounter.UpdateScore();
            ActivateZombie();
            agent.enabled = false;
            GetComponent<Animator>().enabled = false;
            Destroy(collision.gameObject);
            
        }
    }
}

Use OverlapSphere or OverlapBox around enemy, if that sphere contains player’s collider then setDestination of the enemy like

agent.SetDestination(target.position);

float radius = 1;//set this whatever value you like

void Update()
{
     if(IsPlayerInRange(transform.position))
              agent.SetDestination(target.position);
}

bool IsPlayerInRange(Vector3 center){
        Collider[] hitColliders = Physics.OverlapSphere(center, radius);
        foreach (var hitCollider in hitColliders)
        {
            if(hitCollider.gameObject.CompareTag(target.tag)
            {
                   return true;
             }
        }
        return false  
}

This can be optimized a lit bit, if you want

Lastly,
The Code after

Destroy(gameObject) won’t be executed, for that reason, lines below are useless in your code.

scoreCounter.UpdateScore(); ActivateZombie(); agent.enabled = false; GetComponent<Animator>().enabled = false; Destroy(collision.gameObject);

Hello @mustafacomert00 ,
thanks for you quick and very good explanations.
I still receive an error some syntax :slight_smile:

I get this error:

NullReferenceException: Object reference not set to an instance of an object
over.Update ()

on this line: agent.SetDestination(target.position);

you know why?

Best regards
and thank you so much