5 public static class UIExtensionMethods
7 public static Canvas GetParentCanvas(
this RectTransform rt)
9 RectTransform parent = rt;
10 Canvas parentCanvas = rt.GetComponent<Canvas>();
13 while (parentCanvas ==
null || SearchIndex > 50)
15 parentCanvas = rt.GetComponentInParent<Canvas>();
16 if (parentCanvas ==
null)
18 parent = parent.parent.GetComponent<RectTransform>();
25 public static Vector2 TransformInputBasedOnCanvasType(
this Vector2 input, Canvas canvas)
27 if (canvas.renderMode == RenderMode.ScreenSpaceOverlay)
29 return canvas.GetEventCamera().ScreenToWorldPoint(input);
37 public static Vector3 TransformInputBasedOnCanvasType(
this Vector2 input, RectTransform rt)
39 var canvas = rt.GetParentCanvas();
40 if (input ==
Vector2.zero || canvas.renderMode == RenderMode.ScreenSpaceOverlay)
49 RectTransformUtility.ScreenPointToLocalPointInRectangle(
51 input, canvas.GetEventCamera(),
54 Vector3 output = canvas.transform.TransformPoint(movePos);
59 public static Camera GetEventCamera(
this Canvas input)
61 return input.worldCamera ==
null ? Camera.main : input.worldCamera;
Credit Erdener Gonenc - @PixelEnvision.