NavmeshSurface build time too slow on large terrain

Hello

I have a game where a randomly generated 2000x2000 terrain is generated and populated with random objects. As it is random each time, I have to use the navmeshsurface to bake a navmesh at runtime. The only problem is due to the size of the terrain, this can take very long, and of course unity hangs while it bakes so the player will be left waiting for a while.

My question is it is possible to either 1) bake the navmesh in the background progressively without unity hanging while it bakes the entire thing (I looked at navmesh async but it seems to be editor only?) or 2) bake the navmesh in a way that doesn’t take about ten minutes at a time.

I appreciate any input or suggestions on this matter. I have looked around online but most solutions were unable to help my specific game. For example, building a small navmesh area around the player at a time is unusable for the game I am developing, as were some other solutions I tried.

Thank you!

Hello, I have the same problem. I am generating an infinite terrain made up of multiple chunk , each chunk has its own navMeshSurface which is built when the terrain chunk is made. Tho the game keeps freezing for 2-4s each time the player discovers a new chunk. I found about UpdateNavMeshAsync but it is editor only. Also we can’t really use threading because navMeshSurface is not thread safe.

Hi, I had a similar problem.
While I’m still looking for a more efficient solution since I have to generate the navmesh for the whole map due to using user created maps and an AI that may need to pathfind through the whole map depending on what the user wants out of their custom content, this should work well for you.

This Channel/Video has a lot of videos on NavMeshBuilder and generating a navmesh at runtime. The good thing about this method is you can run it asynchronously, use unity jobs to speed the generation up if you have multiple cores, and most importantly, you can control what gets sent to the generator. For your use case, you may want to load the navmesh async around the player and update it outwards depending on your needs.

For your terrain, I suggest splitting it up into sections and only generating a navmesh for the section you are in or limiting the navmesh to a box around your character like in the linked video.

When it came to my version of unity, I had to write Navmesh.CalculateWorldBounds since it was marked as private and not accessible for some reason.

Bounds CalculateWorldBounds(List<NavMeshBuildSource> sources)
{
    // Use the unscaled matrix for the NavMeshSurface
    Matrix4x4 worldToLocal = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
    worldToLocal = worldToLocal.inverse;

    var result = new Bounds();
    foreach (var src in sources)
    {
        switch (src.shape)
        {
            case NavMeshBuildSourceShape.Mesh:
                {
                    var m = src.sourceObject as Mesh;
                    result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, m.bounds));
                    break;
                }
            case NavMeshBuildSourceShape.Terrain:
                {
                    var t = src.sourceObject as TerrainData;
                    result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, new Bounds(0.5f * t.size, t.size)));
                    break;
                }
            case NavMeshBuildSourceShape.Box:
            case NavMeshBuildSourceShape.Sphere:
            case NavMeshBuildSourceShape.Capsule:
            case NavMeshBuildSourceShape.ModifierBox:
                result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, new Bounds(Vector3.zero, src.size)));
                break;
        }
    }
    // Inflate the bounds a bit to avoid clipping co-planar sources
    result.Expand(0.1f);
    return result;
}

private void ResetSources()
{
    // Clear previous sources and bounds
    _navMeshSources.Clear();
    _navMeshData.Clear();
    _navMeshBounds = new Bounds(Vector3.zero, Vector3.zero);

    // Create sources and bounds
    var mask = PhysicsLayer.GetMask(PhysicsLayer.MapObjectEntities);
    List<NavMeshBuildMarkup> modifiers = new List<NavMeshBuildMarkup>();

    // Collect sources of physics colliders, exclude components with NavMeshObstacles
    NavMeshBuilder.CollectSources(null, mask, NavMeshCollectGeometry.PhysicsColliders, 0, modifiers, _navMeshSources);
    _navMeshBounds = CalculateWorldBounds(_navMeshSources);
    _navMeshBounds.size = Vector3.Min(_navMeshBounds.size, new Vector3(15000, 15000, 15000));
}

/// <summary>
/// Use NavMeshBuilder to create a navmesh surface for the given agent id.
/// This should be called asynchronously and sync progress back to the main thread.
/// </summary>
/// <param name="agentID">An integer representing the agent.</param>
private AsyncOperation CreateNavMeshSurfaceAsyncOperation(int agentID, List<NavMeshBuildSource> sources, Bounds bounds)
{
    // Create a new navmeshsurface object
    NavMeshData data = new NavMeshData();
    NavMeshBuildSettings settings = NavMesh.GetSettingsByID(agentID);
    settings.maxJobWorkers = 3;
    settings.overrideTileSize = true;
    settings.tileSize = 256;
    settings.overrideVoxelSize = true;
    settings.voxelSize = 4f;
    settings.minRegionArea = 100;
    settings.buildHeightMesh = true;
    _navMeshData.Add(agentID, data);
    NavMesh.AddNavMeshData(data);
    return NavMeshBuilder.UpdateNavMeshDataAsync(data, settings, sources, bounds);
}

And the code is called here, my use of it is not async as I wait for the navmesh to be done before loading into the map, but it can be done whenever.

if (MapManager.NeedsNavMeshUpdate || _hasNavMeshData == false)
{
    NavMesh.RemoveAllNavMeshData();
    _hasNavMeshData = false;
    if (PhotonNetwork.IsMasterClient && SettingsManager.InGameCurrent.Titan.TitanSmartMovement.Value && gamemodeNeedsNav)
    {
        ResetSources();

        List<int> agentIDs = Util.GetAllTitanAgentIds();
        List<AsyncOperation> operations = new List<AsyncOperation>();
        foreach (int agentID in agentIDs)
        {
            AsyncOperation createOp = CreateNavMeshSurfaceAsyncOperation(agentID, _navMeshSources, _navMeshBounds);
            operations.Add(createOp);
        }

        // Check progress of the operations and use the min progress
        while (operations.Count > 0)
        {
            float minProgress = 1f;
            for (int i = 0; i < operations.Count; i++)
            {
                if (operations[i].isDone)
                {
                    operations.RemoveAt(i);
                    i--;
                }
                else
                    minProgress = Mathf.Min(minProgress, operations[i].progress);
            }
            UIManager.LoadingMenu.UpdateLoading(0.75f + 0.25f * minProgress);
            yield return new WaitForEndOfFrame();
        }

        _hasNavMeshData = true;
    }
}

Here’s what I managed to do for my 1000x1000x1000 terrains, 9 active at a time

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using Unity.AI.Navigation;
using System.Collections;
using System.Linq;

public class ChunkNavmeshBaker : MonoBehaviour
{
    [SerializeField] private bool useSynchronousBake = true; // Default to sync for low quality
    private Unity.AI.Navigation.NavMeshSurface surface;
    private HeightsGenerator generator;
    private Terrain terrain;
    private NavMeshData navMeshData;
    private NavMeshDataInstance navMeshInstance;
    public bool hasStartedGenerating;
    public bool hasFinishedGenerating;

    private static Queue<ChunkNavmeshBaker> bakeQueue = new Queue<ChunkNavmeshBaker>();
    private static bool isBaking;

    void Awake()
    {
        surface = GetComponent<Unity.AI.Navigation.NavMeshSurface>();
        generator = GetComponent<HeightsGenerator>();
        terrain = GetComponent<Terrain>();

        if (surface == null || generator == null || terrain == null || terrain.terrainData == null)
        {
            enabled = false;
            return;
        }

        if (ChunkManagerAnimals.Instance == null)
        {
            enabled = false;
            return;
        }

        ChunkManagerAnimals.Instance.RegisterChunk(gameObject);
    }

    void OnDisable()
    {
        if (ChunkManagerAnimals.Instance != null)
            ChunkManagerAnimals.Instance.UnregisterChunk(gameObject);

        if (navMeshInstance.valid)
            navMeshInstance.Remove();

        if (bakeQueue.Contains(this))
            bakeQueue = new Queue<ChunkNavmeshBaker>(bakeQueue.Where(b => b != this));
    }

    void Update()
    {
        if (!enabled || hasStartedGenerating || !generator.hasFinishedGeneration) return;

        navMeshData = new NavMeshData();
        navMeshInstance = NavMesh.AddNavMeshData(navMeshData);

        bakeQueue.Enqueue(this);
        if (!isBaking)
            StartCoroutine(ProcessBakeQueue());

        hasStartedGenerating = true;
    }

    private static IEnumerator ProcessBakeQueue()
    {
        isBaking = true;
        while (bakeQueue.Count > 0)
        {
            var baker = bakeQueue.Dequeue();
            if (baker == null || !baker.enabled) continue;

            yield return baker.BuildNavMesh();
        }
        isBaking = false;
    }

    private IEnumerator BuildNavMesh()
    {
        if (navMeshData == null)
        {
            navMeshData = new NavMeshData();
            navMeshInstance = NavMesh.AddNavMeshData(navMeshData);
        }

        // Configure low-quality NavMesh settings
        NavMeshBuildSettings settings = surface.GetBuildSettings();
        settings.agentRadius = 0.5f; // Larger radius for simpler paths
        settings.agentHeight = 2f;
        settings.agentSlope = 25f; // Match user requirement
        settings.agentClimb = 0.5f; // Reduced for simplicity
        settings.minRegionArea = 0.1f; // Larger for faster baking
        settings.voxelSize = 0.2f; // Coarser grid for low quality
        settings.maxJobWorkers = 2; // Fewer workers for less CPU

        // Single terrain source
        List<NavMeshBuildSource> sources = new List<NavMeshBuildSource>(1)
        {
            new NavMeshBuildSource
            {
                shape = NavMeshBuildSourceShape.Terrain,
                sourceObject = terrain.terrainData,
                transform = Matrix4x4.TRS(terrain.transform.position, Quaternion.identity, Vector3.one),
                area = 0 // Walkable
            }
        };

        // Tighter bounds for faster computation
        Vector3 terrainSize = terrain.terrainData.size;
        Bounds worldBounds = new Bounds(terrain.transform.position + terrainSize * 0.5f, terrainSize);

        if (useSynchronousBake)
        {
            NavMeshBuilder.UpdateNavMeshData(navMeshData, settings, sources, worldBounds);
        }
        else
        {
            var buildOperation = NavMeshBuilder.UpdateNavMeshDataAsync(navMeshData, settings, sources, worldBounds);
            while (!buildOperation.isDone)
                yield return null;
        }

        hasFinishedGenerating = true;
    }
}