在输入字段中未写入任何内容=>无法按下按钮

时间:2019-04-14 22:08:42

标签: c# unity3d

有人知道一个脚本,如果没有在输入字段中写任何内容=>不能按下按钮,它将在屏幕上显示一条消息

C#统一2d

2 个答案:

答案 0 :(得分:0)

您可以使用https://docs.unity3d.com/ScriptReference/UI.InputField-onValueChanged.html

中的InputField.onValueChanged方法

然后您检查InputField.Text是否为空,然后禁用该按钮,否则启用它。

要禁用按钮,请设置button.interactable = true/false

答案 1 :(得分:0)

您可以使用OnValueChanged,它是在每个字符更改(添加或删除)之后调用的。

在InputField上添加

[RequireComponent(typeof(InputField))]
public class InputValidator : MonoBehaviour
{
    // Here reference the according Button
    // Via the Inspector or script
    public Button targetButton;

    // As little bonus if you want here reference an info box why the input is invalid
    public GameObject infoBox;

    private InputField inputField;

    private void Awake()
    {
        inputField = GetComponent<InputField>();

        // Add callback
        inputField.onValueChanged.AddListener(ValidateInput);
    }

    // Additionally validate the input value everytime 
    // The InputField (this component to be exact) gets enabled in the scene
    private void OnEnable()
    {
        ValidateInput(inputField.text);
    }

    private void ValidateInput(string input)
    {
        // Here you could implement some replace or further validation logic
        // if e.g. only certain characters shall be allowed

        // Enable the button only if some valid input is available
        targetButton.interactable = !string.IsNullOrWhiteSpace(input);

        // just a bonus if you want to show an info box why input is invalid
        if (infoBox) infoBox.SetActive(string.IsNullOrWhiteSpace(input));
    }
}

enter image description here