Skip to content

Instantly share code, notes, and snippets.

@createdbyx
Created February 8, 2016 16:14
Show Gist options
  • Save createdbyx/7532c55ceab0cc39287d to your computer and use it in GitHub Desktop.
Save createdbyx/7532c55ceab0cc39287d to your computer and use it in GitHub Desktop.
Simplified example of adding Tab key support to a Unity3D TextArea
using System;
using UnityEditor;
using UnityEngine;
public class TextAreaTabSupport : EditorWindow
{
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("testa");
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();
}
}
}
this.textA = GUI.TextArea(new Rect(0, 40, 100, 100), this.textA);
if (GUI.GetNameOfFocusedControl() == "testa" && 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