UIExtensionMethods.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /// Credit Simon (simonDarksideJ) Jackson
  2. /// Sourced from - My head
  3. namespace UnityEngine.UI.Extensions
  4. {
  5. public static class UIExtensionMethods
  6. {
  7. public static Canvas GetParentCanvas(this RectTransform rt)
  8. {
  9. RectTransform parent = rt;
  10. Canvas parentCanvas = rt.GetComponent<Canvas>();
  11. int SearchIndex = 0;
  12. while (parentCanvas == null || SearchIndex > 50)
  13. {
  14. parentCanvas = rt.GetComponentInParent<Canvas>();
  15. if (parentCanvas == null)
  16. {
  17. parent = parent.parent.GetComponent<RectTransform>();
  18. SearchIndex++;
  19. }
  20. }
  21. return parentCanvas;
  22. }
  23. public static Vector2 TransformInputBasedOnCanvasType(this Vector2 input, Canvas canvas)
  24. {
  25. if (canvas.renderMode == RenderMode.ScreenSpaceOverlay)
  26. {
  27. return canvas.GetEventCamera().ScreenToWorldPoint(input);
  28. }
  29. else
  30. {
  31. return input;
  32. }
  33. }
  34. public static Vector3 TransformInputBasedOnCanvasType(this Vector2 input, RectTransform rt)
  35. {
  36. var canvas = rt.GetParentCanvas();
  37. if (input == Vector2.zero || canvas.renderMode == RenderMode.ScreenSpaceOverlay)
  38. {
  39. return input;
  40. }
  41. else
  42. {
  43. // Needs work :S
  44. Vector2 movePos;
  45. RectTransformUtility.ScreenPointToLocalPointInRectangle(
  46. rt,
  47. input, canvas.GetEventCamera(),
  48. out movePos);
  49. Vector3 output = canvas.transform.TransformPoint(movePos);
  50. return output;
  51. }
  52. }
  53. public static Camera GetEventCamera(this Canvas input)
  54. {
  55. return input.worldCamera == null ? Camera.main : input.worldCamera;
  56. }
  57. }
  58. }