NxrUICanvas.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.UI;
  4. namespace Nxr.Internal
  5. {
  6. public class NxrUICanvas : MonoBehaviour
  7. {
  8. protected BoxCollider canvasBoxCollider;
  9. protected Rigidbody canvasRigidBody;
  10. private void OnEnable()
  11. {
  12. SetupCanvas();
  13. }
  14. void SetupCanvas()
  15. {
  16. var canvas = GetComponent<Canvas>();
  17. if (!canvas || canvas.renderMode != RenderMode.WorldSpace)
  18. {
  19. return;
  20. }
  21. var canvasRectTransform = canvas.GetComponent<RectTransform>();
  22. var canvasSize = canvasRectTransform.sizeDelta;
  23. var defaultRaycaster = canvas.gameObject.GetComponent<GraphicRaycaster>();
  24. var customRaycaster = canvas.gameObject.GetComponent<NxrUIGraphicRaycaster>();
  25. if (!customRaycaster)
  26. {
  27. customRaycaster = canvas.gameObject.AddComponent<NxrUIGraphicRaycaster>();
  28. }
  29. if (defaultRaycaster && defaultRaycaster.enabled)
  30. {
  31. customRaycaster.ignoreReversedGraphics = defaultRaycaster.ignoreReversedGraphics;
  32. customRaycaster.blockingObjects = defaultRaycaster.blockingObjects;
  33. defaultRaycaster.enabled = false;
  34. }
  35. if (!canvas.gameObject.GetComponent<BoxCollider>())
  36. {
  37. float zSize = 0.1f;
  38. float zScale = zSize / canvasRectTransform.localScale.z;
  39. canvasBoxCollider = canvas.gameObject.AddComponent<BoxCollider>();
  40. canvasBoxCollider.size = new Vector3(canvasSize.x, canvasSize.y, zScale);
  41. canvasBoxCollider.isTrigger = true;
  42. }
  43. if (!canvas.gameObject.GetComponent<Rigidbody>())
  44. {
  45. canvasRigidBody = canvas.gameObject.AddComponent<Rigidbody>();
  46. canvasRigidBody.isKinematic = true;
  47. }
  48. }
  49. void RemoveCanvas()
  50. {
  51. var canvas = GetComponent<Canvas>();
  52. if (!canvas)
  53. {
  54. return;
  55. }
  56. var defaultRaycaster = canvas.gameObject.GetComponent<GraphicRaycaster>();
  57. var customRaycaster = canvas.gameObject.GetComponent<NxrUIGraphicRaycaster>();
  58. //if a custom raycaster exists then remove it
  59. if (customRaycaster)
  60. {
  61. Destroy(customRaycaster);
  62. }
  63. //If the default raycaster is disabled, then re-enable it
  64. if (defaultRaycaster && !defaultRaycaster.enabled)
  65. {
  66. defaultRaycaster.enabled = true;
  67. }
  68. if (canvasBoxCollider)
  69. {
  70. Destroy(canvasBoxCollider);
  71. }
  72. if (canvasRigidBody)
  73. {
  74. Destroy(canvasRigidBody);
  75. }
  76. }
  77. private void OnDestroy()
  78. {
  79. RemoveCanvas();
  80. }
  81. private void OnDisable()
  82. {
  83. RemoveCanvas();
  84. }
  85. }
  86. }