Reputation: 685
I've created a Pause menu for a simple game i'm making. In that pause menu there is a field to enter your username. I'm attempting to check that a username has been entered before the user is allowed to close the pause menu. However both the input.text
and input.TextComponent.text
values are only changed to the typed username when focus is changed away from the input field.
My code is as follows:
public InputField input;
if ((string.IsNullOrEmpty (input.text)) || (input.text == "Enter Username")){
input.textComponent.color = Color.red;
input.text = "Enter Username";
} else {
input.textComponent.color = Color.black;
//hide pause menu and resume game
canvas.gameObject.SetActive (false);
Time.timeScale = 1;
}
This code only works when the user clicks away from the input field box before attempting to close the pause menu. How can I get the text entered as its entered?
I've tried adding GUI.focusControl("")
and GUI.focusControl(null)
before the if statement but this doesn't work either.
Edit :
I've confirmed that the second parameter of the if
statement is working. The menu doesn't close if the entered text is "Enter Username", so i know im checking the text variable correctly. I just dont understand why the if statement returns true if you enter in anything else? I must be missing something
Upvotes: 0
Views: 1330
Reputation: 125245
Both GUI.focusControl("")
and GUI.focusControl(null)
have nothing to do with the Unity's new UI system(uGUI). They are made to work with IMGUI.
If you want to focus on InputField
you can use the code below:
public InputField input;
input.ActivateInputField();
input.Select();
To stop the focus
input.DeactivateInputField();
Do not try to poll InputField.text
. That's not how use it. You do have two options in this case:
1.Subscribe to the InputField
onEndEdit
event.
When the player is done typing and clicks Enter/Return or away, this function will be called. You can then check/compare for the username there. Check #3 from this post.
2.Add a Button that says "check" or "submit". When user is done typing, they will have to click that Button. Subscribe to the Buttons onClick event. When the Button
is clicked you then check/compare for the username there. Check #2 from this post.
If you find another tricky way to do this, it will work but not on Android device. You will end up rewriting the code again.
Upvotes: 1