Hi,
I have a GUI.Box with a textfield.
Is it possible to use focus so when my mouse hovers over the box i can enter text and not when my mouse is outside that box ?
Thanks.
Hi,
I have a GUI.Box with a textfield.
Is it possible to use focus so when my mouse hovers over the box i can enter text and not when my mouse is outside that box ?
Thanks.
You can use the FocusControl function to set the focus, but there isn’t any direct way to detect what the mouse is over. You can, however, test whether the mouse is inside the control’s rectangle using Rect.Contains with the mouse position:-
var textRect = new Rect(...);
text = GUI.TextField(textRect, ...);
if (textRect.Contains(Input.mousePosition)) {
GUI.FocusControl(textFieldName);
} else {
GUI.FocusControl(otherControlName);
}
You can’t set the focus to nothing, so you may need to create a dummy control offscreen that can hold the focus when you don’t need it for anything else.
Thanks for that Andeeee.
I used it to create a search field that looses focus after 3 seconds of inactivity and contains the string “Search” when not used.
GUI.SetNextControlName ("DummyField");
GUI.TextField (Rect ((Screen.width+1), 0, 10, 10), "");
var textRect = new Rect ((Screen.width-150), 0, 150, 20);
var mouseRect = textRect;
mouseRect.y=(Screen.height-mouseRect.y-mouseRect.height); // convert the gui screen coordinates into mouse screen coordinates
if (mouseRect.Contains(Input.mousePosition)) {
if(searchString=="Search") searchString="";
}
GUI.SetNextControlName ("SearchField");
var prevValue=searchString;
searchString = GUI.TextField (textRect, searchString);
if(prevValue!=searchString) {
searchTime=Time.time;
if(searchString.length>1) {
PerformSearch(searchString);
}
}
if (mouseRect.Contains(Input.mousePosition)) {
searchTime=Time.time;
GUI.FocusControl("SearchField");
} else if((searchTime+3)<Time.time) { // loose focus after 3 seconds on inactivity and mouse out
GUI.FocusControl("DummyField");
if(searchString=="") searchString="Search";
}
I still have one question about this though:
I set the style of the textfiled like this:
style = GUI.skin.textArea;
style.normal.background=guiBackground;
style.normal.textColor=Color(0,0.4,0.4);
style.hover.background=guiBackground;
style.hover.textColor=Color(0,0.4,0.4);
style.active.background=guiBackground;
style.active.textColor=Color(0,0.4,0.4);
But when I edit the textfield it returns to the default colors (i.e grey background, white text and orange background behind the selected text.
Can these attributes be set somehow?
There is also a style state called focused that applies when the control has keyboard focus.