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.



You must log in to answer this question.

Browse other questions tagged .