using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
using UnityEngine;
using System;
using System.Text;
using UnityEngine.UI;
using DG.Tweening;
using LitJson;
using UniRx;使用UniRx 插件链接:https://link.zhihu.com/?target=https%3A//assetstore.unity.com/packages/tools/integration/unirx-reactive-extensions-for-unity-17276
public class YanZhen : MonoBehaviour
{
public InputField phoneNumberInput;//手机号输入框
public InputField VerificationcodeInput;//验证码输入框
private Button sent;
private Text times;
private bool ison;
private int time;
private float t;
private float movedis;//移动的距离
private void Start()
{
//查找当前层级下的控件
sent = transform.Find("send").GetComponent<Button>();
times = transform.Find("Timer").GetComponent<Text>();
times.gameObject.SetActive(false);
sent.onClick.AddListener(LoginButton);
movedis = GetComponent<RectTransform>().rect.height;
//使用litjson创建json格式的参数数据
//JsonData data = new JsonData();
//data["phone"] = "13759190279";
}
// Update is called once per frame
/// <summary>
/// 发送验证码
/// </summary>
private void Update()//验证码时间
{
if (ison)
{
times.text = time.ToString();
t += Time.deltaTime;
if (t >= 1)
{
time--;
t = 0;
}
if (time < 0)
{
ison = false;
sent.gameObject.SetActive(true);
times.gameObject.SetActive(false);
}
}
}
public void LoginButton()//方法:点击按钮调用这个方法
{
string strSend = GetInputDate();//获取输入框字符串
//使用litjson创建json格式的参数数据
JsonData data = new JsonData();
data["phone"] = strSend;
if (strSend != null)
{
ison = true;
time = 120;
sent.gameObject.SetActive(false);
times.gameObject.SetActive(true);
byte[] postBytes = System.Text.Encoding.Default.GetBytes(data.ToJson());
StartCoroutine(UnityWebRequestPost("后台url地址", postBytes));
//使用UniRx
ObservableWWW.Post("后台url地址", postBytes, new Dictionary<string, string>() { { "Content-Type", "application/json" } }).Subscribe(result => Debug.Log(result));
}
else
{
ison = false;
sent.gameObject.SetActive(true);
times.gameObject.SetActive(false);
Debug.Log("手机号为空,请输入!");
}
}
public string GetInputDate()//合并字符串方法
{
if (phoneNumberInput.text != "" /*&& VerificationcodeInput.text != ""*/)
{
//获取输入框文本,并剔除掉空格
string userName = phoneNumberInput.text.Replace(" ", "");
//string password = VerificationcodeInput.text.Replace(" ", "");
//将字符串合并
string strSend = userName ;
return strSend;
}
return null;
}
IEnumerator UnityWebRequestPost(string url, byte[] postBytes)
{
UnityWebRequest request = new UnityWebRequest(url, "POST");
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
Debug.Log("Status Code: " + request.responseCode);
if (request.result == UnityWebRequest.Result.ProtocolError || request.result == UnityWebRequest.Result.ConnectionError)
{
Debug.LogError(request.error);
}
else
{
Debug.Log(request.downloadHandler.text);
}
}
unity通过点击按钮获取手机验证码
于 2022-09-03 10:25:20 首次发布