LocalNavMeshBuilder.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using UnityEngine;
  2. using UnityEngine.AI;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using NavMeshBuilder = UnityEngine.AI.NavMeshBuilder;
  6. // Build and update a localized navmesh from the sources marked by NavMeshSourceTag
  7. [DefaultExecutionOrder(-102)]
  8. public class LocalNavMeshBuilder : MonoBehaviour
  9. {
  10. // The center of the build
  11. public Transform m_Tracked;
  12. // The size of the build bounds
  13. public Vector3 m_Size = new Vector3(80.0f, 20.0f, 80.0f);
  14. NavMeshData m_NavMesh;
  15. AsyncOperation m_Operation;
  16. NavMeshDataInstance m_Instance;
  17. List<NavMeshBuildSource> m_Sources = new List<NavMeshBuildSource>();
  18. IEnumerator Start()
  19. {
  20. while (true)
  21. {
  22. UpdateNavMesh(true);
  23. yield return m_Operation;
  24. }
  25. }
  26. void OnEnable()
  27. {
  28. // Construct and add navmesh
  29. m_NavMesh = new NavMeshData();
  30. m_Instance = NavMesh.AddNavMeshData(m_NavMesh);
  31. if (m_Tracked == null)
  32. m_Tracked = transform;
  33. UpdateNavMesh(false);
  34. }
  35. void OnDisable()
  36. {
  37. // Unload navmesh and clear handle
  38. m_Instance.Remove();
  39. }
  40. void UpdateNavMesh(bool asyncUpdate = false)
  41. {
  42. NavMeshSourceTag.Collect(ref m_Sources);
  43. var defaultBuildSettings = NavMesh.GetSettingsByID(0);
  44. var bounds = QuantizedBounds();
  45. if (asyncUpdate)
  46. m_Operation = NavMeshBuilder.UpdateNavMeshDataAsync(m_NavMesh, defaultBuildSettings, m_Sources, bounds);
  47. else
  48. NavMeshBuilder.UpdateNavMeshData(m_NavMesh, defaultBuildSettings, m_Sources, bounds);
  49. }
  50. static Vector3 Quantize(Vector3 v, Vector3 quant)
  51. {
  52. float x = quant.x * Mathf.Floor(v.x / quant.x);
  53. float y = quant.y * Mathf.Floor(v.y / quant.y);
  54. float z = quant.z * Mathf.Floor(v.z / quant.z);
  55. return new Vector3(x, y, z);
  56. }
  57. Bounds QuantizedBounds()
  58. {
  59. // Quantize the bounds to update only when theres a 10% change in size
  60. var center = m_Tracked ? m_Tracked.position : transform.position;
  61. return new Bounds(Quantize(center, 0.1f * m_Size), m_Size);
  62. }
  63. void OnDrawGizmosSelected()
  64. {
  65. if (m_NavMesh)
  66. {
  67. Gizmos.color = Color.green;
  68. Gizmos.DrawWireCube(m_NavMesh.sourceBounds.center, m_NavMesh.sourceBounds.size);
  69. }
  70. Gizmos.color = Color.yellow;
  71. var bounds = QuantizedBounds();
  72. Gizmos.DrawWireCube(bounds.center, bounds.size);
  73. Gizmos.color = Color.green;
  74. var center = m_Tracked ? m_Tracked.position : transform.position;
  75. Gizmos.DrawWireCube(center, m_Size);
  76. }
  77. }