NavMeshAgent Finding New Enemy ON Range/Distance

Hello,
actually when my unit spawns, it goes straight to the Enemy’s base to destroy it, but on it’s way to there: it has to kill Enemies first! instead of killing the enemies, it goes straight to the base, because the enemies are spawning after the Enemy’s base

So the Enemy’s base is the first object on the NavMesh… I am stuck…

I want the unit’s to “see” the Enemy if it’s spawned, when the unit is Walking in a Radius of the Enemy

my Code actually:

using UnityEngine;
using System.Collections;

public class PlayerFindEnemy : MonoBehaviour {

	Transform enemy;
	NavMeshAgent nav;
	


	void Awake ()
	{
		enemy= GameObject.FindGameObjectWithTag ("Enemy").transform;
		
		nav = GetComponent <NavMeshAgent> ();
	}
	
	void FixedUpdate() {

		nav.SetDestination (enemy.position);


	}
}

This is my code,
can I do anything like a “Refresher to activate the NavMesh - if in Range/Distance again” ?

Thank you for reading

I would Use Physics.OverLapSphere

which returns an array of colliders which is shown in the script reference.

this will return all objects so you would have to filter out the array so you only have your enemys (layermask mabye)

then in your Update Function you could have

void Update ()
{
      Collider[] EnemyArray = Physics.OverlapSphere(center, radius, layermask);

     if(EnemyArray.lenght > 0)
     {
          nav.SetDestination (EnemyArray[Random.range(0, EnemyArray.lenght).gameObject]);//this would randomly get one enemy for the agent to follow
     }Else{//else if there are <= 0 enemys just go straight to the base
          nav.SetDestination("what ever you base object is");
     }
}

NOTE: this code probably wont work if you copy paste it its just the logic

hope this helped :slight_smile:

~Scott