Yes it has been asked multiple times, but honestly I couldn’t find a convincing answer. I have been using NavmeshAgent.CalculatePath, but that’s not the correct way: this is not robust for some reason and only works 80% of the time. I saw some people use NavMeshPathStatus.PathComplete, but all the Unity docs have to say about this is “The path terminates at the destination”. What kind of explanation is this, are we being serious here?? I used to be very supportive of Unity’s documentation, but the more I go in depth, the more I get concerned. Anyway, back to the issue: what command can I use to understand if my NavmeshAgent has a path which IS reacheable?
float xVal = Random.Range(posIA.x - lunghezzaZonaPattuglia, posIA.x + lunghezzaZonaPattuglia);
float zVal = Random.Range(posIA.z - larghezzaZonaPattuglia, posIA.z + larghezzaZonaPattuglia);
float yVal = Terrain.activeTerrain.SampleHeight(new Vector3(xVal, 0, zVal));
NavMeshPath sentiero = new NavMeshPath();
bool esisteNavMesh = agenteScript.CalculatePath( new Vector3(xVal, yVal, zVal), sentiero);
while (sentiero.status == NavMeshPathStatus.PathInvalid)
{
//iterate until a valid position within the navmesh is found and continue
}
Sorry, I was making a simple mistake before. This one returns PathComplete most of the time. However, sometimes, when the position Vector3(xVal, yVal, zVal) is slightly outside the Navmesh, then it still returns PathComplete. My NavmeshAgent is just able to reach it because of its relatively large radius.
Hope this code is clear, I am just defining a path, based on random coordinates within a certain range from my AI character. Then I am checking if the path from the position to the AI is valid.
Ok, another mistake: I was checking for a second condition in the while loop. I corrected this. Sometimes the target ends up still slightly outside the Navmesh, but not as much as before and the AI seems to be able to always reach it… fingers crossed
Is there a way to check if a path is possible without calculating a full path, which is an expensive operation? For example, A* Pathfinding Project has a function called IsPathPossible() with the description: “Returns if there is a walkable path from node1 to node2. This method is extremely fast because it only uses precalculated information.”
For AI purposes it’s useful to quickly know if a path to a target can be reached without spending tons of CPU actually testing it by calculating a full path and post-processing it.