亲宝软件园·资讯

展开

Unity工具类之生成文本验证码

人气:1

文本验证码

由于我经常使用Unity进行webgl版本的开发,看到网站上面用户登录有很多的验证码验证。借鉴相关博客,写了Unity的工具类文本验证码,代码如下:

工具类:VerificationCode

using System.Collections;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// 该工具类为:生成验证码
/// 作者:hys
/// 时间:2019.12.30
/// 邮箱:840917807@qq.com
/// </summary>

public class VerificationCode
{

  private static char[] constant =
  {
    '0','1','2','3','4','5','6','7','8','9',
    'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
  };

  /// <summary>
  /// 获取随机生成的验证码
  /// </summary>
  /// <param name="Length">长度</param>
  /// <returns></returns>
  public static string SetDeleKey(int Length)
  {
      StringBuilder newRandom = new StringBuilder(62);
      System.Random rd = new System.Random();
      for (int i = 0; i < Length; i++)
      {
        newRandom.Append(constant[rd.Next(62)]); //rd.Next(62)返回小于62的非负随机数,Append将Length次随机的码进行拼接
      }
    return newRandom.ToString();
  }
  
}

Unity脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HuangVerificationCodeTextScripts : MonoBehaviour
{
  private Text verificationCodeText; //验证码Text.
  private void Awake()
  {
    init();
  }
  void Start()
  {
    
  }
  void Update()
  {
    
  }
  /// <summary>
  /// 进行初始化
  /// </summary>
  private void init()
  {
    verificationCodeText = GameObject.Find("VerificationCodeText").GetComponent<Text>();
  }



  /// <summary>
  /// 生成验证码
  /// </summary>
  /// <param name="length">验证码长度</param>
  /// <returns>字符串类型的验证码</returns>
  public string generateVerificationCode(int length)
  {
    string code= VerificationCode.SetDeleKey(length);
    verificationCodeText.text = code;
    return code;
  }

}
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论