How do you remove the focus from an editor text field when the user clicks outside of it? I know you can set the control focus to null; what I’m not sure about is how to know if the mouse click is outside the focused text field.
As a side note, the text fields are in an editor script, and they are generated on demand; they are not static, rather their amount and position changes as needed.
I read through several posts and I found a working solution after some hours.
I ran into the problem that a focus on a Textfield was not removed while clicking anywhere on the main editor window. This cause many issues if you want to create a editor window with clickable areas, but non GUI elements. I wrote a EditorWindow tool to control about 100 variables over a day and night cycle with manually drawn animation curves.
using UnityEngine;
using UnityEditor;
public class Test : EditorWindow {
public string s;
public Rect windoClickArea = new Rect(0, 0, 200, 200);
[MenuItem("Window/Test")]
static void Init() {
// Get existing open window or if none, make a new one:
Test window = (Test)EditorWindow.GetWindow(typeof(Test));
window.Show();
}
void OnGUI() {
// define click area
Event e = Event.current;
windoClickArea = GUI.Window(0, windoClickArea, drawWindow, "MyWindow");
if (e.type == EventType.MouseDown && windoClickArea.Contains(e.mousePosition)) {
Debug.Log("click");
GUI.FocusControl(null);
}
//click area visible
EditorGUI.DrawRect(windoClickArea, Color.gray);
// Any Text Field over the predefined click area
s = EditorGUILayout.TextField("", s);
}
void drawWindow(int aID) {
// it's a dummy proc
}
}
Activate the focus on the textfield and click on the lite gray area.