Nav Agents randomly disappear before reaching destination

I have a navmesh that’s dynamic when new objects are created, that part works fine. The objects also travel towards the destination just fine. But it seems that if they have difficulty finding the route, or the path is blocked, they destroy themselves and I can’t seem to figure out why.

void Awake()
{
    agent = GetComponent<NavMeshAgent>();     // get nav agent
    spawnEnd = GameObject.Find("end"); // find the end destiation
    agent.destination = spawnEnd.transform.position; // get the location and set the path towards it
}

void FixedUpdate()
{
    if (!agent.pathPending)
    {
        float dist = agent.remainingDistance;
        if (dist <= 0.5f)
        {
            Destroy(gameObject); // destroy only when with in range. This is the only destroy for this object.
        }
    }
}

Hello @Robstao,

I have had the same problem and the reason was that it is not sufficient to check the NavMeshAgent remainingDistance variable. This variable can be zero even if the NavMeshAgent has not reached its Destination. This happens when the agent cannot find a valid path due to some reason. The solution is for you to check two more variables before Destroying the GameObject.

These are:

pathPending Is a path in the process of being computed but not yet ready? (Read Only)

pathStatus The status of the current path (complete, partial or invalid).

So I would rewrite your FixedUpdate as:

 void FixedUpdate()
 {
     if (!agent.pathPending)
     {
         float dist = agent.remainingDistance;
         NavMeshPathStatus status = agent.pathStatus;
         if (status==NavMeshPathStatus.PathComplete &&
             !agent.pathPending && 
             dist <= 0.5f)
         {
             Destroy(gameObject); 
         }
     }
 }

The concept here is to make sure the path is complete, i.e. the agent has a way to reach their destination and to make sure the path is not still being computed. Only after having made sure these two conditions are met, can you be certain that the remainingDistance reflects the actual distance from the agent to its destination.
So, your randomly vanishing objects are actually objects that “randomly” have a remainingDistance zero!