Leave a file, Unity Navigation. Dynamically create NavMesh, dynamic Bake NavMesh, dynamically bake NavMesh

During runtime, create NavMesh dynamically, Bake NavMesh dynamically, and bake NavMesh dynamically.

According to the official demo of Unity, after analysis, it is found that it is not difficult to dynamically create NavMesh navigation.
In fact, it only requires grid information and the range that needs to be created.
It can be considered a fixed
formula. The simplified writing method is as follows. Whether certain information needs to be cached depends on the specific logic implementation.

using UnityEngine;
using UnityEngine.AI;
using System.Collections.Generic;
using NavMeshBuilder = UnityEngine.AI.NavMeshBuilder;


public class NavMeshHelper : MonoBehaviour
{
    private NavMeshDataInstance m_NavMeshDataInstance;

    private void OnDestroy()
    {
        m_NavMeshDataInstance.Remove();
    }

    public void CreateNavMesh(List<Mesh> listMesh, int nSizeX, int nSizeY, int nSizeZ)
    {
        List<NavMeshBuildSource> listBuildSource = new List<NavMeshBuildSource>();
        if (listMesh != null && listMesh.Count > 0)
        {
            for (int i = 0; i < listMesh.Count; i++)
            {
                var s = new NavMeshBuildSource();
                s.shape = NavMeshBuildSourceShape.Mesh;
                s.sourceObject = listMesh[i];
                s.transform = Matrix4x4.identity;
                s.area = 0;
                listBuildSource.Add(s);
            }
        }
        var v3Size = new Vector3(nSizeX, nSizeY, nSizeZ);
        var bounds = new Bounds(Quantize(transform.position, 0.1f * v3Size), v3Size);
        var nmd = new NavMeshData();
        m_NavMeshDataInstance = NavMesh.AddNavMeshData(nmd);

        var defaultBuildSettings = NavMesh.GetSettingsByID(0);
        NavMeshBuilder.UpdateNavMeshData(nmd, defaultBuildSettings, listBuildSource, bounds);
    }

    private Vector3 Quantize(Vector3 v, Vector3 quant)
    {
        float x = quant.x * Mathf.Floor(v.x / quant.x);
        float y = quant.y * Mathf.Floor(v.y / quant.y);
        float z = quant.z * Mathf.Floor(v.z / quant.z);
        return new Vector3(x, y, z);
    }

}


Programming is endless.
Everyone is welcome to communicate. If there is anything unclear or wrong, you can also chat with me privately.
My QQ 334524067 God-like Didi

Guess you like

Origin blog.csdn.net/qq_37776196/article/details/128487457