How to check if my gameobject is created on navigation baked area ?

Hello,

How can i check if my gameobject is created on Navigarion baked area ?
I mean, i have baked my environment using navigation. Now, i have to instantiate enemy prefabs around some radius of my player.I am using random to create enemy prefabs.
So, how can i make sure that, my enemy will be created on that navigation baked area( that blue area ).

Thanks.

Not used this myself but NavMesh.SamplePosition should help.

private NavMeshHit myNavHit;
private float maxDist = 10f;

NavMesh.SamplePosition(Vector3 to check, out myNavHit, maxDist, 1 << NavMesh.GetNavMeshLayerFromName("Default"));

Debug.Log(myNavHit.position);

Haven’t tested the code but it should return the nearest NavMesh position to the Vector3 to check position that you pass it.

You could be really strict with the maxDist and set it to 1 or below if you want the point to be forced really close to your random location.

EDIT:

OK I haven’t used this but as I understand it you give is your Vector3 and it finds the closest point on the NavMesh that is within the maxDist float.

Just try it and Debug.Log to output what it returns. I think myNavHit will be a bool with 1 if it finds somewhere and 0 if it doesn’t and myNavHit.position will be the position on the NavMesh if it finds one in the range.

But you’re 100% correct the documentation is really poor. Had to Google to put that example together.

Anyway the command breaks down to this:

Vector3 to check == your enemies randomly generated position

myNavHit == the returned value and position

maxDist == the maximum distance from your random position to check for a good NavMesh hit

1 << NavMesh.GetNavMeshLayerFromName(“Default”) == the Default NavMesh, change the word Default if you use another NavMesh

EDIT 2:

Just tried it on a random movement script I have and the original post had an error this code works:

NavMesh.SamplePosition(target, out myNavHit, maxDist, 1 << NavMesh.GetNavMeshLayerFromName("Default"));
		
		Debug.Log(" myNavHit = " + myNavHit + " myNavHit.position = " + myNavHit.position + " target = " + target);

Note target is a Vector3 like your random enemy position.

So I was wrong about the bool but it does provide a good NavMesh position.

and this is the output in the console:

36971-navmesh.png