Is it possible to add or modify a navmesh programatically.
For example, if an enemy is chasing and you close a gate, can you set the gate as blocking so the enemy looks for another route.?
Is it possible to add or modify a navmesh programatically.
For example, if an enemy is chasing and you close a gate, can you set the gate as blocking so the enemy looks for another route.?
I’m not sure but I think since unity 5.6 it is possible.
It wasn’t possible before, but in Unity 5.6 it apparently can be done (GitHub, Documentation, Forum).
I ran across this code snippet and altered it a bit – adding/removing works, but I’d be cautious, since the whole functionality still seems like work-in-progress.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class NavMeshOwner : MonoBehaviour {
[SerializeField] LayerMask navMeshLayers;
[SerializeField] Vector3 upDirection = Vector3.up;
NavMeshDataInstance navMeshDataInstance;
void OnEnable() {
// Create new NavMesh whenever the script is enabled
CreateNavMesh();
}
void OnDisable() {
// Delete current NavMesh whenever the script is disabled
RemoveNavMesh();
}
private void CreateNavMesh() {
List<NavMeshBuildSource> buildSources = new List<NavMeshBuildSource>();
NavMeshBuilder.CollectSources(transform, navMeshLayers, NavMeshCollectGeometry.RenderMeshes, 0, new List<NavMeshBuildMarkup>(), buildSources);
NavMeshData navData = NavMeshBuilder.BuildNavMeshData(NavMesh.GetSettingsByID(0), buildSources,
new Bounds(Vector3.zero, new Vector3(10000, 10000, 10000)), Vector3.down,
Quaternion.Euler(upDirection)
);
navMeshDataInstance = NavMesh.AddNavMeshData(navData);
}
private void RemoveNavMesh() {
navMeshDataInstance.Remove();
}
}
Just slap it on an object and set its layer. It roughly works like this:
But as I was sifting through the documentation, I found something which might be more suitable for what you want to do – NavMesh Obstacle. 