Get random point on NavMesh async

by Dusty Roberts   Last Updated July 19, 2017 21:13 PM

I am trying to spawn some entities on a navmesh at runtime. The entities need to spawn at a random point.

Right now i use the following to get a random point:

public Vector3 GetRandomPointOnMesh()
{
    Vector3 randomDirection = UnityEngine.Random.insideUnitSphere * maxDistance;
    randomDirection += transform.position;
    NavMeshHit hit;
    NavMesh.SamplePosition(randomDirection, out hit, maxDistance, 1);

    if (float.IsInfinity(hit.position.x) || float.IsInfinity(hit.position.y) || float.IsInfinity(hit.position.z))
        return GetRandomPointOnMesh();

    return hit.position;
}

My problem here is, some time that random point inside the sphere is not hitting the navmesh, hence the recursive call until it actually hits the navmesh.

How can i make this piece of code run in the background until there is an actual value returned. Cause this holds up the main thread till a value is obtained.



Related Questions





NullReferenceException in StartCoroutine method

Updated November 25, 2016 08:05 AM

Best way to queue animation coroutines in unity

Updated April 15, 2017 00:13 AM