How can I release gui focus via code?

I am working on a game which has a GUI Text Field to capture chat text. The chat system works fine and it outputs what you type in after you press enter. The problem is that I can’t find a way to release the focus from the Text Field and give keyboard input back to the game. This is incredibly frustrating because every time you are done chatting, you have to click on the game window to manually release focus.

I have already tried the following “fixes”:

GUIUtility.keyboard = 0;
//This technically does release focus from the Text Field,
//but the game does not regain focus.

GUI.FocusControl("");
//This does the same thing as the above method.
//GUI.FocusControl cannot give the game focus back, merely change it, at least as
//far as I know.

//I've also tried messing around with enabling/disabling controls,
//the entire GUI interface, and individual GUI calls to see if it'll reset focus.
//No dice.

Does anyone know of a way to give focus back to the main game window so that the Input class can receive input without needing to click on the game window again?

What about:

GUI.UnfocusWindow();

??

Hi, in case someone reads this one day, GUI.FocusControl(“”) works fine to remove focus of gui elements. It either got fixed or people’s logic behind its use was wrong but anyways it does work. (unity 4.3.4)

ps: I use C#, maybe it’s a problem with JS

I dont know if you still need the answer but you can focus any gui element as long as you have previously defined a name for it:

GUI.SetNextControlName ("Input");
submittedName = GUI.TextField (Rect (x, y, a, b), submittedName, 12);
GUI.FocusControl ("Input");

I had the same issue a while ago. I solved it like this (offscreen control for focussing on):

static var hackControlName : String = "hackery129578835432342";

// call this function in OnGUI before calling TextField (only needs to be called once)
static function FocusHack() {
	// fake control used for unfocussing things, since we can't call
	// FocusControl with no arguments and an empty string doesn't work
	GUI.SetNextControlName(hackControlName);
	GUI.Button(Rect(-10000,-10000, 0,0), GUIContent.none);
}

Hey there,

You are removing keyboard focus but you forgot about the hot control.

GUIUtility.hotControl = 0;

This is the value that tells Unity which control has focus. Keyboard control just says which control takes keyboard input. You need to set them both to zero.

Cheers,

whats the confusion? the focus/unfocus question is a simple one, one that everyone who writes code should encounter, and one that everyone will encounter when building a video game. thanks peladovii for the answer. :slight_smile: