NavMeshSourceTag.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using UnityEngine;
  2. using UnityEngine.AI;
  3. using System.Collections.Generic;
  4. // Tagging component for use with the LocalNavMeshBuilder
  5. // Supports mesh-filter and terrain - can be extended to physics and/or primitives
  6. [DefaultExecutionOrder(-200)]
  7. public class NavMeshSourceTag : MonoBehaviour
  8. {
  9. // Global containers for all active mesh/terrain tags
  10. public static List<MeshFilter> m_Meshes = new List<MeshFilter>();
  11. public static List<Terrain> m_Terrains = new List<Terrain>();
  12. void OnEnable()
  13. {
  14. var m = GetComponent<MeshFilter>();
  15. if (m != null)
  16. {
  17. m_Meshes.Add(m);
  18. }
  19. var t = GetComponent<Terrain>();
  20. if (t != null)
  21. {
  22. m_Terrains.Add(t);
  23. }
  24. }
  25. void OnDisable()
  26. {
  27. var m = GetComponent<MeshFilter>();
  28. if (m != null)
  29. {
  30. m_Meshes.Remove(m);
  31. }
  32. var t = GetComponent<Terrain>();
  33. if (t != null)
  34. {
  35. m_Terrains.Remove(t);
  36. }
  37. }
  38. // Collect all the navmesh build sources for enabled objects tagged by this component
  39. public static void Collect(ref List<NavMeshBuildSource> sources)
  40. {
  41. sources.Clear();
  42. for (var i = 0; i < m_Meshes.Count; ++i)
  43. {
  44. var mf = m_Meshes[i];
  45. if (mf == null) continue;
  46. var m = mf.sharedMesh;
  47. if (m == null) continue;
  48. var s = new NavMeshBuildSource();
  49. s.shape = NavMeshBuildSourceShape.Mesh;
  50. s.sourceObject = m;
  51. s.transform = mf.transform.localToWorldMatrix;
  52. s.area = 0;
  53. sources.Add(s);
  54. }
  55. for (var i = 0; i < m_Terrains.Count; ++i)
  56. {
  57. var t = m_Terrains[i];
  58. if (t == null) continue;
  59. var s = new NavMeshBuildSource();
  60. s.shape = NavMeshBuildSourceShape.Terrain;
  61. s.sourceObject = t.terrainData;
  62. // Terrain system only supports translation - so we pass translation only to back-end
  63. s.transform = Matrix4x4.TRS(t.transform.position, Quaternion.identity, Vector3.one);
  64. s.area = 0;
  65. sources.Add(s);
  66. }
  67. }
  68. }