maykl harutyunyan
maykl harutyunyan

Reputation: 86

How to "bake" NavMesh from script at runtime?

how to bake NavMesh in runtime from script. I searched in Google but did not find.
some rendered scene and buttons including bake

Upvotes: 2

Views: 33834

Answers (4)

user2695351
user2695351

Reputation: 186

  1. Make sure that you installed all required packages "AI Navigation"
  2. Then you can build the nav mesh by following the code
private void GenerateNavMesh()
{
    // Use this if you want to clear existing
    //NavMesh.RemoveAllNavMeshData();  
    var settings = NavMesh.CreateSettings();
    var buildSources = new List<NavMeshBuildSource>();
    // create floor as passable area
    var floor = new NavMeshBuildSource
    {
        transform = Matrix4x4.TRS(Vector3.zero, quaternion.identity, Vector3.one),
        shape = NavMeshBuildSourceShape.Box,
        size = new Vector3(10, 1, 10)
    };
    buildSources.Add(floor);
    
    // Create obstacle 
    const int OBSTACLE = 1 << 0;
    var obstacle = new NavMeshBuildSource
    {
        transform = Matrix4x4.TRS(new Vector3(3,0,3), quaternion.identity, Vector3.one),
        shape = NavMeshBuildSourceShape.Box,
        size = new Vector3(1, 1, 1),
        area = OBSTACLE
    }; 
    buildSources.Add(obstacle);
    
    // build navmesh
    NavMeshData built = NavMeshBuilder.BuildNavMeshData(
        settings, buildSources, new Bounds(Vector3.zero, new Vector3(10,10,10)), 
        new Vector3(0,0,0), quaternion.identity);
    NavMesh.AddNavMeshData(built);
}
  1. Enable gizmos and open Window/AI/Navigation toolbox to see navmesh in runtime NavMesh preview

  2. You can see in the code how obstacles are created, if you switch the navigation to the Areas Tab you will see the existing areas or your custom NavMesh Areas

Upvotes: 1

Silis Kleemoff
Silis Kleemoff

Reputation: 1

AlienCode's answer is perfect for baking NavMesh at runtime,
since you can't have both using tags (UnityEditor.AI & UnityEngine.AI).

I created a separate script and used it for baking NavMesh.
I'm not certain if it only works in the editor or in builds though.

Upvotes: -5

AlienCode
AlienCode

Reputation: 55

using UnityEditor.AI; //"Editor" not "Engine"

NavMeshBuilder.ClearAllNavMeshes();
NavMeshBuilder.BuildNavMesh();

Upvotes: 0

theInsomniacGameMaker
theInsomniacGameMaker

Reputation: 106

Currently, Unity doesn't have a way to bake but NavMesh at runtime BUT there is an experimental package that Unity has that allows you bake a NavMesh at runtime. It is very stable package.

There were tutorials made by Brackeys in collaboration with Unity.

The demo project is available for download on GitHub. You can use in the scripts in there to bake a runtime NavMesh.

I would highly recommend watching the tutorial first.

Here is also the link for Unity's site and tutorials on runtime navmesh.

Upvotes: 8

Related Questions