how to check the navmesh agent is reach the destination or not?

how to check the navmesh agent is reach the destination or not?

public Transform target;

NavMeshAgent agent;
// Use this for initialization
void Start ()
{

agent = GetComponent ();

}

// Update is called once per frame
void Update ()
{
agent.SetDestination (target.position);
}

if(reached )

///do some action

so how can i check if reached the target?

I would rather set the agent’s destination every x frames instead of every update. Anyway; this should get you going (untested though)

[SerializeField]float destinationReachedTreshold;
Vector3 target;

void SetTarget(Vector3 position) {
  target = position;
  agent.SetDestination(target);
}

void Update() {
CheckDestinationReached();
}

void CheckDestinationReached() {
  float distanceToTarget = Vector3.Distance(transform.position, target);
  if(distanceToTarget < destinationReachedTreshold)
  {
   print("Destination reached");
  }
}
1 Like

You should be using Vector3.squareMagnitude rather than Vector3.Distance() as it’s much more efficient. Especially important when it’s running each frame.

ya thanks for this answer right now im using Vector3.Distance().right now im changing to Vector3.squareMagnitude as your suggestion

thanks for the reply its helped me alot

2 Likes

You should use the .remainingDistance property instead of the Euclidean distance - the path will typically be longer.
To illustrate a problem with using the Euclidean distance : if the target is on the other side of a wall right next to your character the distance might be 1 unit - but the path to get there might be much longer (e.g. because you have to go through a door to get there)

9 Likes

ok i got it thank u ! im started using now .remainding distance now