Advertisement
Demigiant

Select end of textField in Unity Editor

Aug 20th, 2020 (edited)
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.87 KB | None | 0 0
  1. using System.Reflection;
  2. using UnityEditor;
  3. using UnityEngine;
  4.  
  5. class TestEditor : EditorWindow
  6. {
  7.     [MenuItem("Test/" + _Title)]
  8.     static void ShowWindow() { GetWindow(typeof(TestEditor), false, _Title); }
  9.     const string _Title = "TextEditor";
  10.  
  11.     string _txt = "Some text long 1 22 333 4444 55555 666666 7777777 END";
  12.     bool _focusOnTextRequested;
  13.  
  14.     void OnGUI()
  15.     {
  16.         GUI.SetNextControlName("testText");
  17.         EditorGUILayout.TextField(_txt, EditorStyles.textField);
  18.         float textFieldW = GUILayoutUtility.GetLastRect().width;
  19.         if (_focusOnTextRequested) {
  20.             switch (Event.current.type) {
  21.             case EventType.Layout:
  22.                 EditorGUI.FocusTextInControl("testText");
  23.                 break;
  24.             case EventType.Repaint:
  25.                 _focusOnTextRequested = false;
  26.                 TextEditor tEditor = GetCurrTextEditor();
  27.                 if (tEditor == null) Debug.LogWarning("Couldn't get TextEditor " + Event.current.type);
  28.                 else {
  29.                     float txtW = EditorStyles.textField.CalcSize(new GUIContent(_txt)).x;
  30.                     tEditor.selectIndex = _txt.Length - 3;
  31.                     tEditor.cursorIndex = _txt.Length;
  32.                     if (textFieldW < txtW) {
  33.                         tEditor.scrollOffset = new Vector2(txtW - textFieldW, 0);
  34.                     }
  35.                     Repaint();
  36.                 }
  37.                 break;
  38.             }
  39.         }
  40.  
  41.         if (GUILayout.Button("Select end")) {
  42.             // EditorGUI.FocusTextInControl("testText"); // THID DOESN'T WORK
  43.             _focusOnTextRequested = true;
  44.         }
  45.     }
  46.  
  47.     TextEditor GetCurrTextEditor()
  48.     {
  49.         return typeof(EditorGUI)
  50.             .GetField("activeEditor", BindingFlags.Static | BindingFlags.NonPublic)
  51.             .GetValue(null) as TextEditor;
  52.     }
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement