如何在不指定确切键的情况下读取用户按下的键?
How to read keys that user presses without specifying the exact key?
基本上我需要的是如何缩短我的代码的想法。
所以我现在有一个 IF 系列来获取用户按下的键:
if (Input.GetKeyDown(KeyCode.I))
{
AddToBuffer("I");
}
else if (Input.GetKeyDown(KeyCode.N))
{
AddToBuffer("N");
}
else if (Input.GetKeyDown(KeyCode.F))
{
AddToBuffer("F");
}
它工作得很好,但我想要缩短它,这样就可以保存以缓冲任何键(更好的是,作为字符串)
这样我就不必再指定按下了什么键。
(可能是 TryParse 等)
您可以使用“任意键”:https://docs.unity3d.com/ScriptReference/Input-anyKey.html
if (Input.anyKey)
{
Debug.Log("A key or mouse click has been detected");
// get the pressed key:
String keycode = Event.current.keyCode.ToString();
}
InputString 包含在当前帧上按下的所有键的字符串。建议将字符串分解为字符,如 Unity 文档中的输入字符串示例所示,因为 inputString 可以包含退格符“\b”并输入“\n”字符。
侦听作弊代码的示例可能如下所示:
string cheatCode = "money";
int cheatIndex = 0;
void Update()
{
if(Input.anyKeyDown)
{
foreach (char c in Input.inputString)
{
if(c == cheatCode[cheatIndex])
{
//the next character was entered correctly
Debug.Log("The next character {0} was entered correctly", c);
//On the next key down, check the next character
cheatIndex++;
} else
{
//The character was not correctly entered, reset the cheat index back to the start of the code
Debug.Log("Cheat code invalid. {0} was not the next character", c);
cheatIndex = 0;
}
}
if(cheatIndex == cheatCode.Length)
{
Debug.Log("Cheat code was successfully entered")
}
}
}
我没有在 Unity 中编写和测试它,所以你的里程可能会有所不同。
基本上我需要的是如何缩短我的代码的想法。
所以我现在有一个 IF 系列来获取用户按下的键:
if (Input.GetKeyDown(KeyCode.I))
{
AddToBuffer("I");
}
else if (Input.GetKeyDown(KeyCode.N))
{
AddToBuffer("N");
}
else if (Input.GetKeyDown(KeyCode.F))
{
AddToBuffer("F");
}
它工作得很好,但我想要缩短它,这样就可以保存以缓冲任何键(更好的是,作为字符串)
这样我就不必再指定按下了什么键。
(可能是 TryParse 等)
您可以使用“任意键”:https://docs.unity3d.com/ScriptReference/Input-anyKey.html
if (Input.anyKey)
{
Debug.Log("A key or mouse click has been detected");
// get the pressed key:
String keycode = Event.current.keyCode.ToString();
}
InputString 包含在当前帧上按下的所有键的字符串。建议将字符串分解为字符,如 Unity 文档中的输入字符串示例所示,因为 inputString 可以包含退格符“\b”并输入“\n”字符。
侦听作弊代码的示例可能如下所示:
string cheatCode = "money";
int cheatIndex = 0;
void Update()
{
if(Input.anyKeyDown)
{
foreach (char c in Input.inputString)
{
if(c == cheatCode[cheatIndex])
{
//the next character was entered correctly
Debug.Log("The next character {0} was entered correctly", c);
//On the next key down, check the next character
cheatIndex++;
} else
{
//The character was not correctly entered, reset the cheat index back to the start of the code
Debug.Log("Cheat code invalid. {0} was not the next character", c);
cheatIndex = 0;
}
}
if(cheatIndex == cheatCode.Length)
{
Debug.Log("Cheat code was successfully entered")
}
}
}
我没有在 Unity 中编写和测试它,所以你的里程可能会有所不同。