While using the new NavMesh features that came with Unity 3.5 we found a rather intresting feature. It seems that GameObjects where the Renderer is disabled arent included in the NavMesh. They arent baked at all, and the NavAgents cant find the NavMesh. After filing a bug report our assumptions where confirmed, its supposed to be this way.
The workaround for this feature is to enable all renderers, bake the NavMesh and then disable the renderers again. Luckily Unity is easily extended, which saves us a lot of work. The following script adds a menu item which does this automaticly.
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Unity doesnt bake colliders without an active renderer in the navmesh. So enable the renderer, bake, then disable again.
/// </summary>
public class NavMeshFixer : ScriptableObject
{
[MenuItem("Paladin/Fix Navigation Mesh")]
public static void FixNavMesh()
{
Undo.RegisterSceneUndo("BakeNavMesh");
List<Renderer> disabledObjects = new List<Renderer>(); //Keep a list of old objects
foreach (Renderer item in Object.FindObjectsOfType(typeof(Renderer))) //Loop over all renderers
{
//Check if its marked as NavigationStatic, and it has a disabled renderer
if (GameObjectUtility.AreStaticEditorFlagsSet(item.gameObject, StaticEditorFlags.NavigationStatic)
!item.enabled)
{
disabledObjects.Add(item);
item.renderer.enabled = true; //Temporary enable it.
}
}
NavMeshBuilder.BuildNavMesh(); //Trigger the navmesh to build.
disabledObjects.ForEach( obj => obj.enabled = false ); //Disable the objects again.
Debug.Log(string.Format("Done building navmesh, {0} objects affected.", disabledObjects.Count));
}
}
So the next time you want to build your mesh, and have invisible objects, use the button at Paladin/Fix Navigation Mesh