NavMeshAgent track Player when in Range?

Hello,

So I know absolutely nothing about coding and I need a simple Enemy Script where they just walk around randomly but when the player is close AKA in range, it moves towards them till the player exits their range and goes back to walking around. I’d really like to have code that I can copy and paste into unity.

Thank you for any help!

You’ll have to learn some coding to make a decent game (or whatever you want to do with it). I can point you in the right direction. Copy and pasting won’t get you anywhere.

  • Attach a Nav Mesh Agent to the Enemy. Have it disabled.
  • Call the Nav Mesh Agent in a script attached to the Enemy with Vector3 Distance.

Something like this: (Javascript)

public var player : Transform;  

function Awake () {
player = GameObject.FindGameObjectWithTag ("Player").transform;
nav = GetComponent (UnityEngine.AI.NavMeshAgent);
}

function Update() {
    var distance = Vector3.Distance(player.position, transform.position);
    
        if(distance <= 30) {
           
           nav.enabled = true;
           nav.SetDestination (player.position);
        }
       
        else  {
           this.nav.enabled = false;
        
        }
}

I don’t have the code for random enemy movement, but that’s quite easy to write.

There are plenty of tutorials that Unity provides, which can help you. Please take the time to learn. It will pay off in the long run.

well this might solve your problem

public class Follow : MonoBehaviour {
// Start is called before the first frame update

public List<GameObject> waypoint = new List<GameObject> ();
NavMeshAgent nav;
int index = 0;
int length;
bool range = false;
void Start () {
    nav = GetComponent<NavMeshAgent> ();
    length = waypoint.Count;
    nav.SetDestination (waypoint[index].transform.position);

}

// Update is called once per frame
void Update () {

    Collider[] colliders = Physics.OverlapSphere (transform.position, 10);
    for (int i = 0; i < colliders.Length; i++) {
        if (colliders*.gameObject.name == "player") {*

Debug.Log (“0”);
range = true;
nav.SetDestination (colliders*.gameObject.transform.position);*
break;
} else
range=false;
}
if(range==true)
return;
if (nav.remainingDistance <= nav.stoppingDistance) {
if (index >= length - 1)
index = 0;
else
index++;
nav.SetDestination (waypoint[index].transform.position);
}
}
}