Skip to content

Instantly share code, notes, and snippets.

@josepdecid
Created December 8, 2020 21:01
Show Gist options
  • Save josepdecid/b6c02e33afa016de9bad0e76269eaf21 to your computer and use it in GitHub Desktop.
Save josepdecid/b6c02e33afa016de9bad0e76269eaf21 to your computer and use it in GitHub Desktop.
Unity: Bake a NavMesh dynamically from multiple surfaces
GameObject[] walkableSurfaces = GameObject.FindGameObjectsWithTag("Floor");
CombineInstance[] objectsToCombine = new CombineInstance[walkableSurfaces.Length];
for (int i = 0; i < walkableSurfaces.Length; ++i)
{
MeshFilter meshFilter = walkableSurfaces[i].GetComponent<MeshFilter>();
// Extract mesh from each walkable surface (floor)
objectsToCombine[i].mesh = meshFilter.sharedMesh;
objectsToCombine[i].transform = meshFilter.transform.localToWorldMatrix;
// Disable original single component
walkableSurfaces[i].gameObject.SetActive(false);
}
// New GameObject to merge the floors
GameObject floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
// Combine all meshes and set as the new mesh filter
floor.GetComponent<MeshFilter>().mesh = new Mesh();
floor.GetComponent<MeshFilter>().mesh.CombineMeshes(objectsToCombine);
// Update collider to fit all sub-components
MeshCollider meshCollider = floor.GetComponent<MeshCollider>();
meshCollider.sharedMesh = floor.GetComponent<MeshFilter>().mesh;
// Build dynamic NavMesh
NavMeshSurface surface = floor.AddComponent<NavMeshSurface>();
surface.BuildNavMesh();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment