Search code examples
c#unity-game-enginetextmeshpro

Having problems validating Text Mesh Pro form fields in Unity/C#


I'm trying to validate a TextMeshPro form in Unity, but accessing the fields programmatically seems to be disabling them for some reason.

Here's what I have in my UI Manager script:

using UnityEngine;
using TMPro;


public class UserInputUI : MonoBehaviour
{
    private GameSceneManager gameSceneManager;

    [SerializeField]
    private TMP_InputField nicknameField;
    [SerializeField]
    private TMP_Dropdown suburbField;
    [SerializeField]
    private TMP_Dropdown ageField;


    private void Start()
    {
        gameSceneManager = GameObject.Find("SceneManager").GetComponent<GameSceneManager>();
        if (gameSceneManager == null)
        {
            Debug.LogError("GameSceneManager not found");
        }
    }


    private bool ValidateForm()
    {
        bool nicknameValid = false;
        bool suburbValid = false;
        bool ageValid = false;

        if (string.IsNullOrEmpty(nicknameField.text) == false)
        {
            nicknameValid = true;
        }
        if (suburbField.value == 0)
        {
            nicknameValid = true;
        }
        if (ageField.value == 0)
        {
            nicknameValid = true;
        }

        if (nicknameValid && suburbValid && ageValid)
        {
            return true;
        }
        Debug.LogError("You must fill out all fields");
        return false;
    }


    public void SubmitForm()
    {
        if (ValidateForm())
        {
            gameSceneManager.ChangeScene(2);
        }
    }
}

I've attached the script to the Canvas. If I leave any of the serialised fields unpopulated in the inspector, then that field works as expected. As soon as I drag the reference in, the field stops working - no response to mouse clicks so I can neither type in the text field or open the dropdown.

Has anyone ever seen anything like this before? I've searched around, but I can't find anything that helps.


Solution

  • -sigh- I've found the problem. PEBKAC.

    If I try and submit the form when it doesn't pass the validation, then it throws an error. Unity then helpfully pauses the play window. This means that nothing works no matter how many times I click it.

    This is why you shouldn't code while tired, kids!