c# - 接收任何键盘输入并在 Unity 上使用 Switch 语句

标签 c# unity3d

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

// 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语句的情况下实现任意按键信息检测?

最佳答案

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

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

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 分配更多内存并且必须检查所有可能的键(它的可读性也较差)。

如果你不关心时间和内存性能,那你可以关注this answer .它使用 foreach 循环方法并创建可重用的接口(interface)。


OnGUI

你终于可以 catch Event.current 了(这是一个 unityGUI Event ),就像在 this answer 中解释的那样, 但这样做你会依赖 OnGUI方法。这种方法性能最差。

关于c# - 接收任何键盘输入并在 Unity 上使用 Switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56373604/

相关文章:

c# - P/Pnvoke SetFocus 到一个特定的控件

c# - 网络核心 : register implementation with multiple interfaces and lifestyle Singleton

c# - 使用 C# 进行内核级编程

c# - 如何在数组 C# 中找到模式?

c# - Unity - 如何快进到动画的百分比?

c# - Unity如何让GameObject Speed获得速度

c# - 统一: Need help how to double click detection in c#?

c# - Asp.net 静态对象行为

php - 无法使用 php webservice 连接 unity 和 mysql

c# - Unity Web 请求包装器