Unity:InputField账号密码输入

本文介绍了使用Unity3D中的TMP_InputField实现用户登录界面,包括输入验证和错误消息提示。重点讲解了onValidateInput事件处理和Login函数的异步调用,适合前端开发者了解Unity中表单交互设计。
摘要由CSDN通过智能技术生成

using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class LoginWindow : MonoBehaviour
{
    [SerializeField] private TMP_InputField ipd_user;
    [SerializeField] private TMP_InputField ipd_pwd;
    [SerializeField] private TextMeshProUGUI txt_errorMessage;
    private string username;
    private string password;
    [SerializeField] private Button btn_Login;

    public  void Awake()
    {

        ipd_user.onValidateInput += CheckForEnter;
        ipd_pwd.onValidateInput += CheckForEnter;

        btn_Login.onClick.AddListener(() =>
        {
            Login();
        });

    }

    private char CheckForEnter(string text, int charIndex, char addedChar)
    {
        if (addedChar == '\n')
        {
            Debug.Log("检测到回车");
            Login(false);
            return '\0';
        }
        else
            return addedChar;
    }

    private async void Login(bool sound = true)
    {
        //if (sound)
        //    SoundPlay(audioClick);

        txt_errorMessage.text = "";
        username = ipd_user.text;
        password = ipd_pwd.text;

        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
        {
            txt_errorMessage.text = "用户名或密码不能为空";
        }
        else
        {
            var result = await Entrance.instance.Login(username, password);

            if (result == null)
                txt_errorMessage.text = "请检查网络连接";
            else
            {
                if (result.success)
                    Back();
                else
                    txt_errorMessage.text = "账号密码错误";
            }
        }
    }

    public void Init()
    {
        txt_errorMessage.text = "";
        ipd_user.text = "";
        ipd_pwd.text = "";
        Show();
    }

    private void OnDestroy()
    {
        ipd_user.onValidateInput -= CheckForEnter;
        ipd_pwd.onValidateInput -= CheckForEnter;
    }

 void Back(Action finish = null)
    {
        //CG.DOFade(0, 0.15f);
        /*child1.DOScaleY(0, 0.15f).OnComplete(() =>
        {
            HideType();
            finish?.Invoke();
        });*/
    }

    public void Show()
    {
        gameObject.SetActive(true);
        //CG.alpha = 0;
        /*SoundPlay(audioShow);
        child1.localScale = new Vector3(1, 0, 1);
        //CG.DOFade(1, 0.25f);
        child1.DOScaleY(1, 0.25f);*/
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值