Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Created July 22, 2019 08:39
Show Gist options
  • Save bartwttewaall/44243a123dd13fdded1621c7941f9531 to your computer and use it in GitHub Desktop.
Save bartwttewaall/44243a123dd13fdded1621c7941f9531 to your computer and use it in GitHub Desktop.
Use Unity3D's EventSystem to set or unset focus on a UI element
public TMP_InputField inputField;
float focusReleaseTime;
float focusReleaseCooldown = 0.1f;
public bool HasFocus () {
return EventSystem.current.currentSelectedGameObject == inputField.gameObject;
}
public void SetFocus (bool value) {
if (value && !inputField.isFocused) {
inputField.ActivateInputField ();
ToggleVisibility (true);
} else {
focusReleaseTime = Time.time;
inputField.DeactivateInputField ();
if (!EventSystem.current.alreadySelecting) {
EventSystem.current.SetSelectedGameObject (null);
}
ToggleVisibility (false);
}
}
void ToggleVisibility (bool visible) {
// ..
}
void Start() {
ToggleVisibility (HasFocus ());
}
void Update () {
// use the hardcoded RETURN key for starting and submitting a chat message
if (Input.GetKeyDown (KeyCode.Return) && Time.time >= focusReleaseTime + focusReleaseCooldown) {
// set focus if we don't have focus
if (!HasFocus ()) SetFocus (true);
// but if we have focus with no text then we should release focus
else if (inputField.text.Length == 0) SetFocus (false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment