Replacing a selected part of string in a GUI.Textfield

Hey there folks,

my problem is quite “simple” (famous last words of every coder), yet I struggle to find any useful documentation/examples in the interwebs.

So basically I have this text editor, and it’s supposed to replace a selected part of a string in a TextField/Area into another string, example:

it’s supposed to turn “Hello my name is Ed” into “Hello my name is <ED>”.

Now I can already get which part of the entered string the user has selected with the TextEditor:

TextEditor editor = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);
string selectedText = editor.SelectedText;

So the part of the text is selected and now need to be replaced, and here’s where I have no clue to go about it, because the TextEditor, does have a “ReplaceSelection” method, but it doesn’t seem to work the way I want it (it just changes whats exactly selected). I would appreciate any help/hints towards solving this matter! :slight_smile:

P.S: Just in case it’s not clear, I don’t want to replace the finished string, that would be fairly easy, but the string that is still being written/editted by the user in the Textfield/Area (imagine a WYSIWYG editor-like behavior).

public string txt = “”;

void OnGUI(){
	txt = GUI.TextArea(new UnityEngine.Rect(8, 8, 200, 200), txt);
	TextEditor editor = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);

	GUI.Label(new UnityEngine.Rect(216, 8, 200, 200), string.Format("Selected text: {0}

Pos: {1}
Select pos: {2}",
editor.SelectedText,
editor.pos,
editor.selectPos));

	if (GUI.Button(new UnityEngine.Rect(8, 216, 400, 20), "Replace")){
		txt = txt.Remove(Mathf.Min(editor.pos, editor.selectPos), editor.SelectedText.Length);
		string replaceString = "hahaha";
		txt = txt.Insert(Mathf.Min(editor.pos, editor.selectPos), replaceString);

		editor.pos = Mathf.Min(editor.pos, editor.selectPos);
		editor.selectPos = editor.pos + replaceString.Length;
	}
}

This link helped