I think this makes it easier to read. When we want to get the Distance
between two consecutive entries in the array, and know there are at least two entries (because we dropped out of the method if not), we can just start counting from one.
Since Unity’s documentation doesn’t say if corners[0]
would be the same as the NavMesh Agent’s position, I start by setting the total with the distance from “here” to the first corner.
If the first entry in the array is also “here”, then the distance would be zero, so the result would be the same.
If the first entry in the corner array is already at a distance from “here”, then we didn’t accidentally leave it out of the result.
And if there is a difference (like the current object’s position might be the model’s pivot point but the first entry of the corners is where it hits the NavMesh) then it’s a really small value, so of little consequence. After all we’re not aiming for a precision result but just an approximation for when to cutoff the calculated path from being a viable target position to walk to with one click…
private float GetPathLength(NavMeshPath path)
{
// Not enough corners for calculating a distance
if (path.corners.Length < 2) return 0f;
float totalDistance = Vector3.Distance(transform.position, path.corners[0]);
for (int i = 1; i < path.corners.Length; i++)
{
totalDistance += Vector3.Distance(path.corners[i - 1], path.corners[i]);
}
return totalDistance;
}
(And I just saw that it would be better to first check the amount of corners before starting off with the first Distance()
, just in case… since NavMesh.CalculatePath()
returned true
(or we wouldn’t be calling GetPathLength()
it should be safe to assume the array can’t be empty, but still… Also, it’s one Distance()
call less…)