Unity Navmesh.SamplePosition Failing?

I’m trying to have some NavMeshAgents chose a random location on the navigation mesh when they reach their destination, but what happens is that the NavMesh.SamplePosition is returning a Vector3 of (Infinity, Infinity, Infinity).

What am I doing wrong?

The method actually works perfectly fine. The documentation is just terrible. You need to bitshift the layer. Typically you are trying to query the default layer so it would look something like this:

NavMesh.SamplePosition(vec, out hit, dist, 1 << NavMesh.GetNavMeshLayerFromName(“Default”));

I had the same problem. All the pathfinding worked perfectly, and then suddently “Infinity” every time.

The reason is the third argument is SamplePosition. In my code (copypaste from manual) it was 1.0f. And it’s actually MAX DISTANCE to find a navmesh point from source point. So if your source point is higher than 1 from the ground, SamplePosition will return false.

Just increase the third argument. make it 2 or 5 or set it relative to unit (maybe you have the Giant Enemy Crab, which center is over 9000 units above the ground).