接收任何键盘输入并与 Unity 上的 Switch 语句一起使用 [英] Receive any Keyboard input and use with Switch statement on Unity

查看:92
本文介绍了接收任何键盘输入并与 Unity 上的 Switch 语句一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想使用 if 语句.为了简单和性能,我想使用 switch case 并执行该方法.我希望检测到所有键盘输入.但是有没有什么方法可以传递任何按键信息?我目前的做法是:

I don't want to use if statement. For simplicity and performance I want to use switch case and execute that method. I want all the keyboard Input to get detected. But is there any method that will pass any key press information? My current approach is :

// Update is called once per frame
void Update()
{
    char a = Input.GetKey();//anything like this method?
    switch (a)
    {
        case 'a':
                //print'';
                break;
        case 'b':
                //print'';
                break;
        default:
            break;
    }

}

如何在没有 if 语句的情况下实现任意按键信息检测?

How can I achieve this any key press information detection without if statement?

推荐答案

最佳解决方案 - 使用 Input.inputString

您可以使用 Input.inputString 来捕捉输入的键盘输入最后一帧作为字符串.

Best Solution - Use Input.inputString

You may use Input.inputString to catch the keyboard input entered in the last frame as a string.

void Update()
{
    //get the input
    var input = Input.inputString;
    //ignore null input to avoid unnecessary computation
    if (!string.IsNullOrEmpty(input))
        //logic related to the char pressed
        Debug.Log("Pressed char: " + Input.inputString);
}

<小时>

其他解决方案

Foreach 循环

您可能会使用 foreach 循环方法,就像其他答案中建议的那样,但它的性能不佳.Foreach 分配更多内存,并且必须检查所有可能的键(它也不太可读).

You might use foreach loop approach, like suggested in other answers, but it is not as performant. Foreach allocates more memory and must check against all possible keys (it is also less readable).

如果你不关心时间和内存性能,那么你可以关注这个答案.它使用 foreach 循环方法并创建可重用的界面.

If you do not care about time and memory performance, then you might follow this answer. It uses the foreach loop approach and create a reusable interface.

OnGUI

最后,您可以捕获 Event.current(这是一个 unityGUI事件),如这个答案,但这样做你会依赖OnGUI 方法.这种方法的性能最差.

Finally you could catch the Event.current (that is a unityGUI Event), like explained in this answer, but doing so you would rely on the OnGUI method. This method has the worst performance.

这篇关于接收任何键盘输入并与 Unity 上的 Switch 语句一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆