Advertisement
Guest User

DropdownHorizontalFitter

a guest
Sep 10th, 2015
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.13 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3.  
  4. public class DropdownHorizontalFitter : MonoBehaviour
  5. {
  6.     void Start()
  7.     {
  8.         RectTransform rectTransform = (RectTransform)transform;
  9.  
  10.         float width = rectTransform.rect.width;
  11.         float scrollbarWidth = 0;
  12.  
  13.         //  If there's a scrollbar, get its width
  14.         Scrollbar scrollbar = transform.parent.GetComponentInChildren<Scrollbar>();
  15.         if (scrollbar != null)
  16.         {
  17.             scrollbarWidth = ((RectTransform)scrollbar.transform).rect.width;
  18.         }
  19.  
  20.         //  Iterate through the texts (in the items) and find out which text + padding (+ scrollbar) is the longest,
  21.         //  and set width to that, if it's longer than the caption width
  22.         Text[] texts = GetComponentsInChildren<Text>();
  23.         for (int i = 0; i < texts.Length; i++)
  24.         {
  25.             RectTransform offsetTransform = (RectTransform)texts[0].transform;
  26.             width = Mathf.Max(width, Mathf.Abs(offsetTransform.offsetMin.x) + Mathf.Abs(offsetTransform.offsetMax.x) + texts[i].preferredWidth + scrollbarWidth);
  27.         }
  28.  
  29.         //  Set new width
  30.         rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, width);
  31.  
  32.         //  Get right edge of dropdown and right edge of root canvas,
  33.         //  if the dropdown goes off the canvas on the right, make it go to the left instead
  34.         Canvas rootCanvas = GetComponentInParent<Canvas>();
  35.         if (rootCanvas != null)
  36.         {
  37.             while (!rootCanvas.isRootCanvas)
  38.             {
  39.                 rootCanvas = rootCanvas.transform.parent.GetComponentInParent<Canvas>();
  40.             }
  41.  
  42.             Vector3[] corners = new Vector3[4];
  43.  
  44.             rectTransform.GetWorldCorners(corners);
  45.             float rectTransformRightEdge = corners[2].x;
  46.  
  47.             ((RectTransform)rootCanvas.transform).GetWorldCorners(corners);
  48.             float rootCanvasRightEdge = corners[2].x;
  49.  
  50.             if (rectTransformRightEdge > rootCanvasRightEdge)
  51.             {
  52.                 rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, 0, width);
  53.             }
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement