Search code examples
c#unity-game-engineinput-fieldhint

Hint/Error message for InputField (Unity)


With Android/Java you can use something like this

myEditText.setError("This field cannot be blank");

to show an error message/hint for the entered text in an EditText:

enter image description here

Is there anything similar for Unity's InputField in C# or do you have to make your own (e.g. with a text that auto-vanishes after 5 seconds)?

Is there a commonly used design/layout to show a message like that in Unity/Windows games?


Solution

  • No, but you can make your own!

    Add a new add a GameObject as a child to the GameObject your InputField is attached to. You can edit this GameObject however much you want, but just adding a UnityEngine.UI.Text should be fine, and make sure that the new GameObject is not active by defualt.

    Now add a script to the GameObject with your InputField, and add something like this to it:

    public void OnStoppedEditing(string text) {
      if (text == "") { 
        errorWindow.SetActive(true); 
        errorText.text = "This field cannot be blank"; 
    
      }
    
    }
    public void Start() {
       //adds a listener that runs OnStoppedEditing when you stop editing myField
       myField.onEndEdit.AddListener(delegate {OnStoppedEditing(myField); }); 
    
       myField = gameObject.getComponent<InputField>();
       errorText = errorWindow.getComponent<Text>();
    }
    public GameObject errorWindow;
    Text errorText; 
    InputField myField;
    

    make sure that you add "using UnityEngine.UI;" to the top of the script

    Save the script and apply errorWindow to the child GameObject that you created!

    Please note that I didnt test this code (I dont have access to a pc with unity right now) so if it has any errors just ask :)