Tanoda
UILineConnector.cs
Go to the documentation of this file.
1
3
5{
6 [AddComponentMenu("UI/Extensions/UI Line Connector")]
7 [RequireComponent(typeof(UILineRenderer))]
8 [ExecuteInEditMode]
9 public class UILineConnector : MonoBehaviour
10 {
11
12 // The elements between which line segments should be drawn
13 public RectTransform[] transforms;
14 private Vector2[] previousPositions;
15 private RectTransform canvas;
16 private RectTransform rt;
17 private UILineRenderer lr;
18
19 private void Awake()
20 {
21 canvas = GetComponentInParent<RectTransform>().GetParentCanvas().GetComponent<RectTransform>();
22 rt = GetComponent<RectTransform>();
23 lr = GetComponent<UILineRenderer>();
24 }
25
26 // Update is called once per frame
27 void Update()
28 {
29 if (transforms == null || transforms.Length < 1)
30 {
31 return;
32 }
33 //Performance check to only redraw when the child transforms move
34 if (previousPositions != null && previousPositions.Length == transforms.Length)
35 {
36 bool updateLine = false;
37 for (int i = 0; i < transforms.Length; i++)
38 {
39 if (!updateLine && previousPositions[i] != transforms[i].anchoredPosition)
40 {
41 updateLine = true;
42 }
43 }
44 if (!updateLine) return;
45 }
46
47 // Get the pivot points
48 Vector2 thisPivot = rt.pivot;
49 Vector2 canvasPivot = canvas.pivot;
50
51 // Set up some arrays of coordinates in various reference systems
52 Vector3[] worldSpaces = new Vector3[transforms.Length];
53 Vector3[] canvasSpaces = new Vector3[transforms.Length];
54 Vector2[] points = new Vector2[transforms.Length];
55
56 // First, convert the pivot to worldspace
57 for (int i = 0; i < transforms.Length; i++)
58 {
59 worldSpaces[i] = transforms[i].TransformPoint(thisPivot);
60 }
61
62 // Then, convert to canvas space
63 for (int i = 0; i < transforms.Length; i++)
64 {
65 canvasSpaces[i] = canvas.InverseTransformPoint(worldSpaces[i]);
66 }
67
68 // Calculate delta from the canvas pivot point
69 for (int i = 0; i < transforms.Length; i++)
70 {
71 points[i] = new Vector2(canvasSpaces[i].x, canvasSpaces[i].y);
72 }
73
74 // And assign the converted points to the line renderer
75 lr.Points = points;
76 lr.RelativeSize = false;
77 lr.drivenExternally = true;
78
79 previousPositions = new Vector2[transforms.Length];
80 for (int i = 0; i < transforms.Length; i++)
81 {
82 previousPositions[i] = transforms[i].anchoredPosition;
83 }
84 }
85 }
86}
Vector2[] Points
Points to be drawn in the line.
Credit Erdener Gonenc - @PixelEnvision.