Skip to content

Instantly share code, notes, and snippets.

@createdbyx
Last active February 8, 2016 16:11
Show Gist options
  • Save createdbyx/553ab97270ce7e97b3f6 to your computer and use it in GitHub Desktop.
Save createdbyx/553ab97270ce7e97b3f6 to your computer and use it in GitHub Desktop.
More advanced example of adding Tab key support to a Unity3D TextArea
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class TextAreaTabSupport : EditorWindow
{
private Vector2 scroll;
private int lastKBFocus = -1;
private string textA = string.Empty;
private string textB = string.Empty;
private string textC = string.Empty;
[MenuItem("Test/Text Area Tab Support")]
public static void ShowWindow()
{
GetWindow<TextAreaTabSupport>().Show();
}
public void OnGUI()
{
var current = Event.current;
GUI.SetNextControlName("scroller");
using (var scroll = new GUI.ScrollViewScope(new Rect(Vector2.zero, new Vector2(330, 150)), this.scroll, new Rect(Vector2.zero, new Vector2(330, 150))))
{
this.scroll = scroll.scrollPosition;
if (GUI.GetNameOfFocusedControl() == "testa" && this.lastKBFocus == GUIUtility.keyboardControl)
{
if (current.type == EventType.KeyDown || current.type == EventType.KeyUp)
{
if (current.isKey && (current.keyCode == KeyCode.Tab || current.character == '\t'))
{
if (current.type == EventType.KeyUp)
{
var te = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);
if (!current.shift)
{
for (var i = 0; i < 4; i++)
{
te.Insert(' ');
}
}
else
{
var min = Math.Min(te.cursorIndex, te.selectIndex);
var index = min;
var temp = te.text;
for (var i = 1; i < 5; i++)
{
if ((min - i) < 0 || temp[min - i] != ' ')
{
break;
}
index = min - i;
}
if (index < min)
{
te.selectIndex = index;
te.cursorIndex = min;
te.ReplaceSelection(string.Empty);
}
}
this.textA = te.text;
}
current.Use();
}
}
}
using (new GUI.GroupScope(new Rect(0, 0, 110, 110)))
{
GUI.SetNextControlName("testa");
this.textA = GUI.TextArea(new Rect(0, 4, 100, 100), this.textA);
}
if (this.lastKBFocus != GUIUtility.keyboardControl && (current.type == EventType.KeyDown || current.type == EventType.KeyUp))
{
this.lastKBFocus = GUIUtility.keyboardControl;
}
GUI.SetNextControlName("testb");
this.textB = GUI.TextArea(new Rect(110, 40, 100, 100), this.textB);
GUI.SetNextControlName("testc");
this.textC = GUI.TextField(new Rect(220, 40, 100, 30), this.textC);
if (GUI.Button(new Rect(10, 110, 50, 25), "Click"))
{
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment