ARPlaneVisualizer.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace UnityARInterface
  5. {
  6. public class ARPlaneVisualizer : ARBase
  7. {
  8. [SerializeField]
  9. private GameObject m_PlanePrefab;
  10. [SerializeField]
  11. private int m_PlaneLayer;
  12. public int planeLayer { get { return m_PlaneLayer; } }
  13. private Dictionary<string, GameObject> m_Planes = new Dictionary<string, GameObject>();
  14. void OnEnable()
  15. {
  16. m_PlaneLayer = LayerMask.NameToLayer ("ARGameObject");
  17. ARInterface.planeAdded += PlaneAddedHandler;
  18. ARInterface.planeUpdated += PlaneUpdatedHandler;
  19. ARInterface.planeRemoved += PlaneRemovedHandler;
  20. }
  21. void OnDisable()
  22. {
  23. ARInterface.planeAdded -= PlaneAddedHandler;
  24. ARInterface.planeUpdated -= PlaneUpdatedHandler;
  25. ARInterface.planeRemoved -= PlaneRemovedHandler;
  26. }
  27. protected virtual void CreateOrUpdateGameObject(BoundedPlane plane)
  28. {
  29. GameObject go;
  30. if (!m_Planes.TryGetValue(plane.id, out go))
  31. {
  32. go = Instantiate(m_PlanePrefab, GetRoot());
  33. // Make sure we can pick them later
  34. foreach (var collider in go.GetComponentsInChildren<Collider>())
  35. collider.gameObject.layer = m_PlaneLayer;
  36. m_Planes.Add(plane.id, go);
  37. }
  38. go.transform.localPosition = plane.center;
  39. go.transform.localRotation = plane.rotation;
  40. go.transform.localScale = new Vector3(plane.extents.x, 1f, plane.extents.y);
  41. }
  42. protected virtual void PlaneAddedHandler(BoundedPlane plane)
  43. {
  44. if (m_PlanePrefab)
  45. CreateOrUpdateGameObject(plane);
  46. }
  47. protected virtual void PlaneUpdatedHandler(BoundedPlane plane)
  48. {
  49. if (m_PlanePrefab)
  50. CreateOrUpdateGameObject(plane);
  51. }
  52. protected virtual void PlaneRemovedHandler(BoundedPlane plane)
  53. {
  54. GameObject go;
  55. if (m_Planes.TryGetValue(plane.id, out go))
  56. {
  57. Destroy(go);
  58. m_Planes.Remove(plane.id);
  59. }
  60. }
  61. }
  62. }