I am working on a project that involves a simple chat interface. I want the chat to be focused with the “enter/return” keydown event, and unfocused similarly. I realize that there is no specific way to drop focus from one particular control. As a workaround I had intended to simply make the GUI element appear and focus on enter and then disappear after a second enter keypress.
My problem lies in the fact that GUI.FocusControl seems to be locking program flow to within the function that generates the chat window. I cannot have a toggle in Update() because once focus has been set to the text field, Update stops running until focus is dropped or the field stops drawing. If I put the condition to drop the text field within OnGUI or the window drawing function it is called multiple times nearly instantaneously and thus drops the field before it is even visible (since OnGUI is called multiple times per frame…).
Is there any chance that I am overlooking something obvious? Something as simple as ingame chat has to have been done before -.-
Hmm, your question was slightly confusing but I think I get the gist of it. I recently built a chat and command system, and GUI.FocusControl was one of my worst experiences in coding. I spent hours trying to get my head around it, but this solution ended up working. OK, so tell me if any of this needs changing to suit your needs:
private var returnPressed : boolean = false;
private var changeFocus : boolean = false;
function Update () {
if (Input.GetKeyDown(KeyCode.Return) || returnPressed) {
changeFocus = true;
returnPressed = false;
}
}
function OnGUI () {
if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return) {
returnPressed = true;
}
if (changeFocus) {
GUI.SetNextControlName("focusChange");
if (GUI.GetNameOfFocusedControl != "focusChange") {
GUI.FocusControl("focusChange");
} else {
GUI.FocusControl("");
}
changeFocus = false;
}
}
I haven’t tested this, so there’s always potential for stupid errors and I doubt it’s perfect, but we shall see. Tell me how you go!
Hope this helps, Klep
I came up with a weird solution to the problem, but a solution non-the-less. I added a timer to the my Update function where I checked if (Input.GetKeyDown(KeyCode.Return)). I removed the condition that my input field had to have more than 0 characters entered before focus could be dropped. I then forced OnGUI to check if the time elapsed between the original GetKeyDown and the following was greater than 0.2 seconds (although even shorter would work).
All this does is prevent OnGUI from accepting the same KeyDown as the one from Update.