我不想使用 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/