- Home /
GUI.FocusControl & GUI.SetNextControlName doesn't work
I am trying to get set the focus to a text field when the user presses backslash. Here's the code I have tried to implement, but when I press backslash the textfield is not focused. I have indeed confirmed that the unity is detecting the key press so that's not the issue:
void OnGUI ()
{
if(Application.loadedLevel != 0 && Application.loadedLevel != 1)
{
#region chat
//chat stuff
GUI.SetNextControlName("localChat");
localChatMsg = GUI.TextField(new Rect(Screen.width*0.01f, Screen.height*0.96f, 180, 22), localChatMsg, 100);
if(GUI.Button(new Rect(Screen.width*0.25f, Screen.height*0.96f, 50, 22), "Send"))
{
_Mukizuserver.SendLocalMessage(localChatMsg);
localChatMsg = "";
GUIUtility.keyboardControl = 0;
}
if(Event.current.keyCode == KeyCode.Return && Event.current.type == EventType.KeyUp)
{
_Mukizuserver.SendLocalMessage(localChatMsg);
localChatMsg = "";
GUIUtility.keyboardControl = 0;
}
#endregion
}
void Update ()
{
//enable chat by pressing backslash
if(Input.GetKeyUp(KeyCode.Backslash))
{
GUI.FocusControl("localChat");
}
}
Comment
Answer by unimechanic · Oct 03, 2014 at 02:36 PM
Thanks @unimechanic !! I fixed the problem by checking whether the backslash key was pressed in update and turning a boolean variable true. Then in OnGUI I focused the control to the chat in an if statement and reverted the boolean to false.
Answer by JasonWorks · Mar 22, 2018 at 05:17 PM
I've also come across this issue - I believe GUI.FocusControl doesn't work outside of OnGUI.