Check if there is a NavMesh in the scene

Hi,

I’d like to check if there is a NavMesh in the scene, I thought this code would work.

private var _navMesh : UnityEngine.AI.NavMesh[];

    _navMesh = FindObjectsOfType.<UnityEngine.AI.NavMesh>();

    if(_navMesh == null)
    {
        return;
    }

Thanks.

OR …

_navMesh = FindOfType.<UnityEngine.AI.NavMesh>();

I feel like there must be a simpler way to do this, but…

NavMeshHit hit;
if (NavMesh.SamplePosition(Vector3.zero, out hit, 1000.0f, NavMesh.AllAreas)) {
Vector3 result = hit.position;
navMeshAvailable = true;
} else {
navMeshAvailable = false;
}

This seems to work for me. It’s kind of hacky because I think it may be possible that there is some circumstance where you have a huge scene with no NavMesh within 1000 meters of Vector3.zero.

The use case is avoiding that warning you get when you try to enable a NavMeshAgent on a scene with no NavMesh baked yet: “Failed to create agent because there is no valid NavMesh”

I have a character controller that can use NavMesh Agents or standard transform velocity, and I want it to autodetect which method it should use on scene load based on whether or not it can find a NavMesh in the scene.

2 Likes