- Home /
Unity UI: I want the InputField to show a placeholder, but clear it when the field is selected
I am using a InputField to allow my player to enter a name for their character. I set the InputField's Image component to have full transparency so that just the Placeholder text shows, because it overlays some graphics and I don't want a big box on the screen.
What I would like to do is make it so that when my player clicks the InputField, the Placeholder text goes from saying "Character Name" to blank. and then goes back to "Character Name" if the player doesn't enter anything.
It already blanks out fine as soon as the first text character is typed into the field, I just want that to happen as soon as the player clicks into the field....
Answer by Solorino78 · Apr 26, 2021 at 10:08 AM
Hello,
I faced the same problem and to resolve this I used the "Text mesh pro input field", you got 2 events "OnSelect" and "OnDeselect".
You attach this script to the gameobject with the input field :
public class UIInputFieldController : MonoBehaviour
{
/// <summary>
/// Define if the place holder is hide on selection
/// </summary>
[SerializeField]
private bool _isPlaceholderHideOnSelect;
/// <summary>
/// The input field
/// </summary>
[SerializeField]
private TMP_InputField _inputField;
/// <summary>
/// The input field select
/// </summary>
public void OnInputFieldSelect()
{
if (this._isPlaceholderHideOnSelect == true)
{
this._inputField.placeholder.gameObject.SetActive(false);
}
}
/// <summary>
/// The input field deselect
/// </summary>
public void OnInputFieldDeselect()
{
if (this._isPlaceholderHideOnSelect == true)
{
this._inputField.placeholder.gameObject.SetActive(true);
}
}
}
Don't forget to link the events and the script.
Thank you! I used this code in my project. I removed however the "this." why did you add them if I may ask?
It's just a na$$anonymous$$g convention I use to differentiate the variables from the class and the local ones.