daily pastebin goal
94%
SHARE
TWEET

Unity InputFieldMod v1.0

a guest Feb 9th, 2017 1,434 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.EventSystems;
  4. using System.Collections;
  5. using System.Text.RegularExpressions;
  6.  
  7. // InputFieldMod v1.0
  8. // Thanks to:
  9. // mjkkirschner https://github.com/mjkkirschner/XYZ-Visual-Programming/blob/master/Assets/UI/ExpandingInputField.cs
  10. // zxkne http://answers.unity3d.com/questions/1195865/ui-scrollrect-mask-not-hiding-input-field-caret-an.html#answer-1309469
  11.  
  12. [ExecuteInEditMode]
  13. [RequireComponent(typeof(InputField))]
  14. [RequireComponent(typeof(LayoutElement))]
  15. public class InputFieldMod : UIBehaviour {
  16.     [Range(1,50)]
  17.     public int textRows = 1;
  18.  
  19.     // optional scroll rect parent (manually linked)
  20.     public ScrollRect scrollRect;
  21.     RectTransform scrollRectTransform;
  22.     RectTransform ScrollRectTransform { get { if (scrollRect && !scrollRectTransform) scrollRectTransform = scrollRect.GetComponent<RectTransform>(); return scrollRectTransform; } }
  23.  
  24.     // parent gameobjects
  25.     CanvasScaler scaler;
  26.     float ScaleFactor { get { if (!scaler) scaler = GetComponentInParent<CanvasScaler>(); return scaler ? scaler.scaleFactor : 1; } }
  27.     HorizontalOrVerticalLayoutGroup parentLayout;
  28.     HorizontalOrVerticalLayoutGroup ParentLayout { get { parentLayout = transform.parent.GetComponent<HorizontalOrVerticalLayoutGroup>(); return parentLayout; } }
  29.  
  30.     // current gameobject components
  31.     LayoutElement inputElement;
  32.     LayoutElement InputElement { get { if (!inputElement) inputElement = GetComponent<LayoutElement>(); return inputElement; } }
  33.     InputField inputField;
  34.     InputField InputField { get { if (!inputField) inputField = GetComponent<InputField>(); return inputField; } }
  35.     RectTransform rect;
  36.     RectTransform Rect { get { if (!rect) rect = GetComponent<RectTransform>(); return rect; } }
  37.  
  38.     // child gameobjects
  39.     CanvasRenderer caret;
  40.  
  41.     // string replacers
  42.     private Regex colorTags = new Regex("<[^>]*>");
  43.     private Regex keyWords = new Regex("and |assert |break |class |continue |def |del |elif |else |except |exec |finally |for |from |global |if |import |in |is |lambda |not |or |pass |print |raise |return |try |while |yield |None |True |False ");
  44.     private Regex operators = new Regex("<=|>=|!=");
  45.     public Regex definedTriggers { get; set; }
  46.  
  47.     // register input field events on start
  48.     protected override void Start() {
  49.         InputField.onValueChanged.AddListener(new UnityEngine.Events.UnityAction<string>(ResizeInput));
  50.         InputField.onEndEdit.AddListener(new UnityEngine.Events.UnityAction<string>(Highlight));
  51.         InputField.onValueChanged.AddListener(new UnityEngine.Events.UnityAction<string>(RemoveTags));
  52.     }
  53.  
  54.     #if UNITY_EDITOR
  55.     Vector2 offsetMin;
  56.     Vector2 offsetMax;
  57.     int fontSize;
  58.     int textRowsOld;
  59.     Vector2 scrollSize;
  60.     #endif
  61.  
  62.     void Update() {
  63.         #if UNITY_EDITOR
  64.         //(editor only) size adjustment if values have changed
  65.         if (textRows <= 0) textRows = 1;
  66.         if (offsetMin == Vector2.zero || offsetMin != InputField.textComponent.rectTransform.offsetMin ||
  67.             offsetMax == Vector2.zero || offsetMax != InputField.textComponent.rectTransform.offsetMax ||
  68.             fontSize == 0 || fontSize != InputField.textComponent.fontSize ||
  69.             textRowsOld == 0 || textRows != textRowsOld) {
  70.  
  71.             fontSize = InputField.placeholder.GetComponent<Text>().fontSize = InputField.textComponent.fontSize;
  72.             offsetMin = InputField.placeholder.rectTransform.offsetMin = InputField.textComponent.rectTransform.offsetMin;
  73.             offsetMax = InputField.placeholder.rectTransform.offsetMax = InputField.textComponent.rectTransform.offsetMax;
  74.             if (scrollRect && textRowsOld != textRows) Debug.LogError("INPUT FIELD MOD: Text rows has no effect while Scroll Rect linked.");
  75.             textRowsOld = textRows;
  76.             ResizeInput();
  77.         }
  78.  
  79.         // (editor only) adapt size to scroll rect
  80.         if (scrollRect && (scrollSize == Vector2.zero || scrollSize != ScrollRectTransform.rect.size)) {
  81.             scrollSize = ScrollRectTransform.rect.size;
  82.             ResizeInput();
  83.         }
  84.         #endif
  85.  
  86.         // fix text selection masking
  87.         if (!caret) {
  88.             Transform caretTransform = InputField.transform.Find(InputField.transform.name + " Input Caret");
  89.             if (caretTransform) {
  90.                 Graphic graphic = caretTransform.GetComponent<Graphic>();
  91.                 if (!graphic) {
  92.                     Image image = caretTransform.gameObject.AddComponent<Image>();
  93.                     image.color = new Color(0, 0, 0, 0);
  94.                 }
  95.             }
  96.         }
  97.     }
  98.  
  99.     // string operations
  100.     public void Highlight(string text) {
  101.         InputField.text = colorTags.Replace(InputField.text, @"");
  102.         InputField.text = keyWords.Replace(InputField.text, @"<color=blue>$&</color>");
  103.         InputField.text = operators.Replace(InputField.text, @"<color=red>$&</color>");
  104.         if (definedTriggers != null) {
  105.             InputField.text = definedTriggers.Replace(InputField.text, @"<color=green>$&</color>");
  106.         }
  107.         InputField.MoveTextEnd(false);
  108.     }
  109.  
  110.     private void RemoveTags(string text) {
  111.         InputField.text = colorTags.Replace(InputField.text, @"");
  112.     }
  113.  
  114.     // get text padding (min max vertical offset for size calculation)
  115.     float VerticalOffset { get { return InputField.placeholder.rectTransform.offsetMin.y - InputField.placeholder.rectTransform.offsetMax.y; } }
  116.  
  117.  
  118.     // resize input field recttransform
  119.     void ResizeInput() {
  120.         ResizeInput(InputField.text);
  121.     }
  122.  
  123.     void ResizeInput(string text) {
  124.         // current text settings
  125.         TextGenerationSettings settings = InputField.textComponent.GetGenerationSettings(InputField.textComponent.rectTransform.rect.size);
  126.         settings.generateOutOfBounds = false;
  127.         // current text rect height
  128.         float currentHeight = InputField.textComponent.rectTransform.rect.height;
  129.         // preferred text rect height
  130.         float preferredHeight = (new TextGenerator().GetPreferredHeight(InputField.text, settings) / ScaleFactor) + VerticalOffset;
  131.         float defaultHeight;
  132.  
  133.         // default text rect height (fit to scroll parent or expand to fit text)
  134.         if (scrollRect) defaultHeight = ScrollRectTransform.rect.height;
  135.         else defaultHeight = ((new TextGenerator().GetPreferredHeight("", settings) * textRows ) / ScaleFactor) + VerticalOffset;
  136.  
  137.         // force resize
  138.         if (currentHeight < preferredHeight || currentHeight > preferredHeight) {
  139.             if (preferredHeight > defaultHeight) {
  140.                 if (ParentLayout) {
  141.                     InputElement.preferredHeight = preferredHeight;
  142.                 } else {
  143.                     Rect.sizeDelta = new Vector2(Rect.rect.width, preferredHeight);
  144.                 }
  145.             } else {
  146.                 if (ParentLayout) {
  147.                     InputElement.preferredHeight = defaultHeight;
  148.                 } else {
  149.                     Rect.sizeDelta = new Vector2(Rect.rect.width, defaultHeight);
  150.                 }
  151.             }
  152.         } else {
  153.             if (ParentLayout) {
  154.                 InputElement.preferredHeight = defaultHeight;
  155.             } else {
  156.                 Rect.sizeDelta = new Vector2(Rect.rect.width, defaultHeight);
  157.             }
  158.         }
  159.  
  160.         // update scroll rect position
  161.         if (scrollRect) StartCoroutine(ScrollMax());
  162.     }
  163.  
  164.     // update scroll rect position (after Layout was rebuilt)
  165.     IEnumerator ScrollMax() {
  166.         yield return new WaitForEndOfFrame();
  167.         if (scrollRect != null) scrollRect.verticalNormalizedPosition = 0;
  168.     }
  169. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top