Find cursor position in a TextArea

Hi guys
Im having some troubles adding the ability to use tab spacing in my Text Area.

Im trying to catch the tab event and then use string.Insert() to add the tab into the text, this works as intended except that to use insert as you all probably know you must enter an index value for where the insertion will be.

My question is, How can i find the correct index value for the string in my Text Area based off where the cursor is?

Hi, you can get the TextEditor to get the information you need. Unfortunately this documentation has fallen behind a bit, but check out this example:

using UnityEngine;
using System.Collections;

public class GUITextAreaEditorExample : MonoBehaviour
    public string txt = "";
    void OnGUI()
        txt = GUI.TextArea(new Rect(8, 8, 200, 200), txt);
        TextEditor editor = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);
        GUI.Label(new Rect(216, 8, 200, 200), string.Format("Selected text: {0}

Pos: {1}
Select pos: {2}",

        if (GUI.Button(new Rect(8, 216, 400, 20), "Insert Tab"))
            txt = txt.Insert(editor.pos, "	");

This is how I do it :

private int carretPosCode = 0;
    private bool tabCode = false;
    TextEditor editor;

    textAreaCode = GUI.TextArea(new Rect(0,0,500,300),textAreaCode);
    editor = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);
        if(Event.current.type == EventType.keyDown ){
        						textAreaCode = textAreaCode.Insert(editor.selectPos, "	");
        						carretPosCode = editor.selectPos;
        if ( Event.current.keyCode == KeyCode.Tab && Event.current.type == EventType.keyUp  ) {	
        						tabCode = true;
        if(tabCode && Event.current.type == EventType.Layout){
        						editor.pos = carretPosCode+2;
        						editor.selectPos = carretPosCode+2;
        						tabCode = false;

How does it know which text to pay attention to? I am busy trying to use this for an editor script so that my client can decide which text to make bold, But for some reason it only works when i have this at the top of my OnGUI method. When i try to use this with Data i.e in a custom class like Name, Description etc it always says the selected text is empty?

Is this global or ?