BoxColliderSizeFitToCanvas.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using UnityEngine;
  2. namespace Rokid.UXR.Interaction
  3. {
  4. [ExecuteAlways]
  5. [RequireComponent(typeof(BoxCollider))]
  6. public class BoxColliderSizeFitToCanvas : MonoBehaviour
  7. {
  8. [SerializeField]
  9. private float rectZ = 0.001f;
  10. [SerializeField]
  11. private BoxCollider boxCollider;
  12. [SerializeField]
  13. private BoxProximityField boxProximity;
  14. [SerializeField]
  15. private Canvas targetCanvas;
  16. private Vector3 preSize = Vector3.one;
  17. private Vector3 prePos = Vector3.zero;
  18. private void Start()
  19. {
  20. if (targetCanvas == null)
  21. targetCanvas = GetComponentInChildren<Canvas>();
  22. if (boxCollider == null)
  23. boxCollider = transform.GetComponent<BoxCollider>();
  24. if (boxProximity == null)
  25. boxProximity = transform.GetComponentInChildren<BoxProximityField>();
  26. }
  27. private void Update()
  28. {
  29. if (boxCollider != null && boxProximity != null && targetCanvas != null)
  30. {
  31. Vector3 size = targetCanvas.GetComponent<RectTransform>().rect.size * targetCanvas.transform.localScale;
  32. size[2] = rectZ;
  33. Vector3 position = targetCanvas.transform.position;
  34. if (preSize != size || prePos != position)
  35. {
  36. preSize = size;
  37. prePos = position;
  38. boxCollider.size = size;
  39. Transform tsf = boxProximity.transform;
  40. boxProximity.transform.localScale = new Vector3(size.x, size.y, rectZ);
  41. boxProximity.transform.position = targetCanvas.transform.position;
  42. boxCollider.center = new Vector3(targetCanvas.transform.localPosition.x, targetCanvas.transform.localPosition.y, 0);
  43. }
  44. }
  45. }
  46. }
  47. }