Skip to content

Instantly share code, notes, and snippets.

@mihakrajnc
Last active February 22, 2019 06:40
Show Gist options
  • Save mihakrajnc/db8da69d45286ee0c5eef2488c1945c5 to your computer and use it in GitHub Desktop.
Save mihakrajnc/db8da69d45286ee0c5eef2488c1945c5 to your computer and use it in GitHub Desktop.
A NavMesh factory for Mapbox.
using System.Collections.Generic;
using Mapbox.Unity.MeshGeneration.Data;
using Mapbox.Unity.MeshGeneration.Enums;
using Mapbox.Unity.MeshGeneration.Factories;
using UnityEngine;
using UnityEngine.AI;
[CreateAssetMenu(menuName = "Mapbox/Factories/Custom/NavMesh Factory")]
public class NavMeshFactory : AbstractTileFactory
{
[SerializeField] private int navMeshSettingsIndex;
private NavMeshBuildSettings settings;
private NavMeshData navMeshData;
private readonly Dictionary<UnityTile, NavMeshBuildSource> buildSources =
new Dictionary<UnityTile, NavMeshBuildSource>();
internal override void OnInitialized()
{
settings = NavMesh.GetSettingsByIndex(navMeshSettingsIndex);
navMeshData = new NavMeshData();
NavMesh.AddNavMeshData(navMeshData);
}
internal override void OnRegistered(UnityTile tile)
{
if (tile.HeightDataState == TilePropertyState.Loading)
{
tile.OnMeshDataChanged += UpdateNavMesh;
}
else
{
UpdateNavMesh(tile);
}
}
internal override void OnUnregistered(UnityTile tile)
{
buildSources.Remove(tile);
// UpdateNavMesh(tile);
}
private void UpdateNavMesh(UnityTile tile)
{
if (buildSources.ContainsKey(tile))
{
buildSources.Remove(tile);
}
buildSources.Add(tile, new NavMeshBuildSource()
{
shape = NavMeshBuildSourceShape.Mesh,
sourceObject = tile.MeshFilter.mesh,
transform = tile.transform.localToWorldMatrix,
area = 0
});
NavMeshBuilder.UpdateNavMeshDataAsync(navMeshData, settings, new List<NavMeshBuildSource>(buildSources.Values),
new Bounds(tile.Map.Root.position, Vector3.one * 100000));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment