Tanoda
UIExtensionMethods.cs
Go to the documentation of this file.
1
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
12 int SearchIndex = 0;
13 while (parentCanvas == null || SearchIndex > 50)
14 {
15 parentCanvas = rt.GetComponentInParent<Canvas>();
16 if (parentCanvas == null)
17 {
18 parent = parent.parent.GetComponent<RectTransform>();
19 SearchIndex++;
20 }
21 }
22 return parentCanvas;
23 }
24
25 public static Vector2 TransformInputBasedOnCanvasType(this Vector2 input, Canvas canvas)
26 {
27 if (canvas.renderMode == RenderMode.ScreenSpaceOverlay)
28 {
29 return canvas.GetEventCamera().ScreenToWorldPoint(input);
30 }
31 else
32 {
33 return input;
34 }
35 }
36
37 public static Vector3 TransformInputBasedOnCanvasType(this Vector2 input, RectTransform rt)
38 {
39 var canvas = rt.GetParentCanvas();
40 if (input == Vector2.zero || canvas.renderMode == RenderMode.ScreenSpaceOverlay)
41 {
42 return input;
43 }
44 else
45 {
46 // Needs work :S
47 Vector2 movePos;
48
49 RectTransformUtility.ScreenPointToLocalPointInRectangle(
50 rt,
51 input, canvas.GetEventCamera(),
52 out movePos);
53
54 Vector3 output = canvas.transform.TransformPoint(movePos);
55 return output;
56 }
57 }
58
59 public static Camera GetEventCamera(this Canvas input)
60 {
61 return input.worldCamera == null ? Camera.main : input.worldCamera;
62
63 }
64 }
65}
Credit Erdener Gonenc - @PixelEnvision.