Search Unity

Building NavMeshes in separate thread?

Discussion in 'AI & Navigation Previews' started by kulesz, Aug 22, 2017.

  1. kulesz

    kulesz

    Joined:
    Jul 1, 2012
    Posts:
    131
    Does the new NavMeshSurface ("Components for Runtime NavMesh Building") supports asynchronous NavMesh building, or everyting must be created in Unity thread?
    Is it possible to fire BuildNavMesh as async task and do not stall main thread?
     
  2. AshyB

    AshyB

    Joined:
    Aug 9, 2012
    Posts:
    173
    Did you ever find out if there is an async operation? I know theres UpdateNavMesh() but that only works after the navmesh has already been built...

    Also appears you can't use static batching gameobjects with navmeshsurface...?
     
  3. MadeFromPolygons

    MadeFromPolygons

    Joined:
    Oct 5, 2013
    Posts:
    3,268
  4. laurentlavigne

    laurentlavigne

    Joined:
    Aug 16, 2012
    Posts:
    5,289
    Navmesh build is async by default but needs to be called from the main thread.
     
  5. AshyB

    AshyB

    Joined:
    Aug 9, 2012
    Posts:
    173
    Ah think I figured it out.

    Just startcoroutine and pass the navmeshsurface to the coroutine.

    Code (csharp):
    1.  
    2.         // called by startcoroutine whenever you want to build the navmesh
    3.         IEnumerator BuildNavmesh(NavMeshSurface surface)
    4.         {
    5.             // get the data for the surface
    6.             var data = InitializeBakeData(surface);
    7.  
    8.             // start building the navmesh
    9.             var async = surface.UpdateNavMesh(data);
    10.  
    11.             // wait until the navmesh has finished baking
    12.             yield return async;
    13.  
    14.             Debug.Log("finished");
    15.  
    16.             // you need to save the baked data back into the surface
    17.             surface.navMeshData = data;
    18.  
    19.             // call AddData() to finalize it
    20.             surface.AddData();
    21.         }
    22.  
    23.         // creates the navmesh data
    24.         static NavMeshData InitializeBakeData(NavMeshSurface surface)
    25.         {
    26.             var emptySources = new List<NavMeshBuildSource>();
    27.             var emptyBounds = new Bounds();
    28.  
    29.             return UnityEngine.AI.NavMeshBuilder.BuildNavMeshData(surface.GetBuildSettings(), emptySources, emptyBounds, surface.transform.position, surface.transform.rotation);
    30.         }
    31.  
     
  6. MadeFromPolygons

    MadeFromPolygons

    Joined:
    Oct 5, 2013
    Posts:
    3,268
    No, coroutines are not seperate threads. They are run on the main thread.
     
    SamFernGamer4k, Yorp and kulesz like this.
unityunity