- Home /
Manually set ControlID to built-in controls ?
Is there a way to manually set a controlID to one of Unity's built-in controls (i.e. Buttons, text fields, etc) ?
I am writing a custom control that behave like a normal label when not focused and switch to a text field when I detect a mouse click. Problem is, if I use GUI/EditorGUI.TextField(...), they internally set GUIUtility.hotControl
and I lose my custom control's focus.
My code looks like this for now :
public static string EditableLabel(Rect position, string label)
{
int controlId = GUIUtility.GetControlID(GUIHashes.EditableLabel, FocusType.Keyboard, position);
EditorGUIUtility.AddCursorRect(position, MouseCursor.Text, controlId);
GUI.SetNextControlName("EditableLabel");
switch(Event.current.GetTypeForControl(controlId))
{
case EventType.Repaint:
if(GUIUtility.hotControl == controlId)
label = GUI.TextArea(position, label);
else
GUI.Label(position, label, Styles.LabelBoldItalicStyle);
break;
case EventType.MouseDown :
if(Event.current.button == 0 && position.Contains(Event.current.mousePosition))
{
GUIUtility.hotControl = controlId;
EditorGUI.FocusTextInControl("EditableLabel");
}
break;
case EventType.MouseUp:
if(Event.current.button == 0 && GUIUtility.hotControl == controlId)
{
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
}
break;
}
return label;
}
I'm making tools right now and the lack of IMGUI solid documention is seriously hindering...
I am wondering if I have to manually handle a UnityEngine.TextEditor
and just completely bybass built-in controls, but it feels redundant...
Answer by steinbitglis · Jun 10, 2017 at 09:45 AM
So far, I prefer the technique of accessing GUI.DoTextField(...) through reflection, and mimic GUI.TextField(...) with the appropriate changes.
Just checking: you're using ILSpy to analyze UnityEngine.dll and UnityEditor.dll, right? It's super handy in these situations.
Here's some code I found with ILSpy.
// UnityEngine.GUI
public static string TextField(Rect position, string text, int maxLength, GUIStyle style)
{
GUIContent gUIContent = GUIContent.Temp(text);
GUI.DoTextField(position, GUIUtility.GetControlID(FocusType.Keyboard, position), gUIContent, false, maxLength, style);
return gUIContent.text;
}