其他分享
首页 > 其他分享> > Unity中实现依次按下字符按键进行测试

Unity中实现依次按下字符按键进行测试

作者:互联网

测试时需要一些开启一些作弊的方法来提高测试的效率,比如键盘依次按下一串字符去实现某个功能,依次按下addcoin去增加金币等等

using UnityEngine;
using System;

public class DebugAndTest : MonoBehaviour
{
    public string str;//连续按下的按键
    private int strIndex;//下标

    private void Update()
    {
        KeyCode keyCode = GetKeyCode();
        //防止一直检测
        if (keyCode == KeyCode.None)
        {
            return;
        }

        if (JudgeIsEqual(keyCode))
        {
            strIndex++;
        }
        else
        {
            strIndex = 0;
        }

        if (strIndex >= str.Length)
        {
            strIndex = 0;

            //依次按下按键后执行的操作
            Method();
        }
    }

    /// <summary>
    /// 得到当前按下的按键
    /// </summary>
    /// <returns></returns>
    private KeyCode GetKeyCode()
    {
        if (Input.anyKeyDown)
        {
            foreach (KeyCode k in Enum.GetValues(typeof(KeyCode)))
            {
                if (Input.GetKeyDown(k))
                {
                    return k;
                }
            }
        }
        return KeyCode.None;
    }

    /// <summary>
    /// 判定按下的按键是否相同
    /// </summary>
    /// <param name="keyCode">按下的按键</param>
    /// <returns></returns>
    private bool JudgeIsEqual(KeyCode keyCode)
    {
        //得到按键的常规值
        string key = keyCode.ToString();
        if (keyCode.ToString().Contains("Alpha"))
        {
            key = keyCode.ToString().Split('a')[1];
        }

        //得到进行判定的值
        string upperChar = Char.ToUpper(str[strIndex]).ToString();
        string lowerChar = Char.ToLower(str[strIndex]).ToString();

        bool isEqual = key.Equals(upperChar) || key.Equals(upperChar);
        return isEqual;
    }

    /// <summary>
    /// 依次按下按键后执行的操作
    /// </summary>
    private void Method()
    {
       Debug.Log("开启作弊操作");
    }
}

 

标签:Unity,private,KeyCode,按下,按键,keyCode,strIndex
来源: https://blog.csdn.net/LLLLL__/article/details/105562169