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);

    void Update()

        if (Vector3.Distance(target.position, transform.position) < 1.5f)

    private void OnCollisionEnter(Collision collision)
        if (collision.transform.tag == "Weapon")
            agent.enabled = false;
            GetComponent<Animator>().enabled = false;

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


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

void Update()

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

This can be optimized a lit bit, if you want

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