Custom editor, want features from GUILayout.TextArea and EditorGUILayout.TextArea

I’m creating a custom editor for rich text, and am partially stumped using the TextEditor to check the SelectedText, while keeping the ability to access shortcuts for stuff like undo and save.

GUILayout.TextArea is able to give access to TextEditor for the information I want in order to add rich text to a selection, but prevents any shortcuts from being detected.

TextEditor txtedt = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);

EditorGUI.BeginChangeCheck();
string changedText = GUILayout.TextArea(currentText);//prevents shortcuts from being detected
if(EditorGUI.EndChangeCheck()){
    Undo.RegisterCompleteObjectUndo(this, "change text");
    currentText = changedText
}
Debug.Log(txtedt.SelectedText)//prints currently highlighted text I would expect

EditorGUILayout.TextArea allows shortcuts to be detected, but TextEditor does not relay any information to TextEditor

TextEditor txtedt = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);

EditorGUI.BeginChangeCheck();
string changedText = EditorGUILayout.TextArea(currentText);//does not relay changes to txtedt
if(EditorGUI.EndChangeCheck()){
    Undo.RegisterCompleteObjectUndo(this, "change text");
    currentText = changedText
}
Debug.Log(txtedt.SelectedText)// is empty

Is there any way to have both the ability to get information on the SelectedText, while being able to access shortcuts? Am I using EditorGUILayout.TextArea or GUILayout.TextArea wrongly?

Im using Unity 2021.1.16f in case that matters.

Well, using “GetStateObject” on the current control id is actually a hack that counts on the exact internal implementation of the TextArea (which in turns calls GUI.DoTextField). There it actually registers a TextEditor for this field as state object.

The EditorGUI version actually uses a recycled static TextEditor for all text fields. Unfortunately this is an internal static field so it’s not exposed anywhere. There’s also the static activeEditor field which holds the currently active editor. However that is alsi private. Of course you can use reflection to get that editor instance.

1 Like

Thank you for the links, not sure if it’s an optimal solution, but reflection got the job done.

Now the only mystery left is, why GUILayout.TextArea, or any of its text fields, prevent shortcuts from triggering.