|
| 1 | +// Custom Contect menu for UI Image component (in WorldSpace UI canvas) |
| 2 | +// used for creating outline for panel (image) using LineRenderer |
| 3 | + |
| 4 | +using UnityEngine; |
| 5 | +using UnityEditor; |
| 6 | +using UnityEngine.UI; |
| 7 | + |
| 8 | +namespace UnityLibrary |
| 9 | +{ |
| 10 | + public class CreateOutlineForPanelEditor : MonoBehaviour |
| 11 | + { |
| 12 | + [MenuItem("CONTEXT/Image/Create Outline For Panel")] |
| 13 | + static void DoubleMass(MenuCommand command) |
| 14 | + { |
| 15 | + // get reference |
| 16 | + Image comp = (Image)command.context; |
| 17 | + if (comp == null) |
| 18 | + { |
| 19 | + Debug.LogError("No Image component found.."); |
| 20 | + return; |
| 21 | + } |
| 22 | + |
| 23 | + // TODO check that its worlspace canvas |
| 24 | + |
| 25 | + // get worldspace borders, FIXME get root canvas, instead of parent |
| 26 | + var canvasRect = comp.transform.parent.GetComponent<Canvas>().GetComponent<RectTransform>(); |
| 27 | + Vector3[] corners = new Vector3[4]; |
| 28 | + canvasRect.GetWorldCorners(corners); |
| 29 | + |
| 30 | + var line = comp.transform.GetComponent<LineRenderer>(); |
| 31 | + if (line == null) |
| 32 | + { |
| 33 | + Debug.LogError("Missing LineRenderer component"); |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + if (line.useWorldSpace == true) |
| 38 | + { |
| 39 | + Debug.LogWarning("LineRenderer has worlspace enabled, disabling it"); |
| 40 | + line.useWorldSpace = false; |
| 41 | + } |
| 42 | + |
| 43 | + // set line points |
| 44 | + line.positionCount = corners.Length + 1; |
| 45 | + line.SetPositions(corners); |
| 46 | + // connect last and first |
| 47 | + line.SetPosition(line.positionCount - 1, corners[0]); |
| 48 | + |
| 49 | + // convert worldspace to localspace |
| 50 | + for (int i = 0, len = line.positionCount; i < len; i++) |
| 51 | + { |
| 52 | + var worldPos = line.GetPosition(i); |
| 53 | + var localPos = canvasRect.transform.InverseTransformPoint(worldPos); |
| 54 | + line.SetPosition(i, localPos); |
| 55 | + } |
| 56 | + |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments