实现的是:按下任意按键,返回按键的名称
根据参考资料1
1.方法 OnGUI() 函数的时间Event方法
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void OnGUI() {
Event e = Event.current;
if (e.isKey)
Debug.Log("Detected key code: " + e.keyCode);
}
}
按一次按键,会显示 2次相同的
上述代码,把事件 直接 放在 除了OnGUI函数 以外的函数都 会显示 没有实例化 物体。
有个 事件 监听 的组件,推导出方法3
除了少量按键无法识别,大多数按键是可以识别的
2.方法 对每个按键进行IF语句判断,判断当前按下的任意 键
参考资料2,本文不再赘述
遍历 每个按键的代码
using UnityEngine;using System;using System.Collections;using System.Collections.Generic;public void detectPressedKeyOrButton(){foreach(KeyCode kcode in Enum.GetValues(typeof(KeyCode))){if (Input.GetKeyDown(kcode))Debug.Log("KeyCode down: " + kcode);}}
// You can use this FetchKey() Method if you like,// it's from the top of my head but It// should return which key is currently pressed down,// although it will only return the first// key it finds, you can modify it to return// KeyCode[] containing all keys currently held// down if you need to.KeyCode FetchKey(){e = System.Enum.GetNames(typeof(KeyCode)).Length;for(int i = 0; i < e; i++){if(Input.GetKey((KeyCode)i)){return (KeyCode)i;}}return KeyCode.None;
3.
结合资料1和3,可以得出以下代码
void SetCurrent()
{
Event e = Event.current;
if (e.isKey)
{
Debug.Log(" BBB "+ e.keyCode);
}
}
SetCurrent()函数 事件,在 游戏蛮牛-手册和Unity3D的中文手册
中都没有说明
第一次是成功的,不知道为什么 再测试,就失败了
4.
Event.KeyboardEvent 键盘事件
和方法1类似当你需要检查是否某个键被按下时(可能带有修改键)这个很有用,key的字符串是键的名字(同输入管理器一样),任选任意数量修改键前缀:& = Alternate,^ = Control,% = Command/Windows key, # = Shift
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void OnGUI() {
GUILayout.Label("Press Enter To Start Game");
if (Event.current.Equals(Event.KeyboardEvent("[enter]")))
Application.LoadLevel(1);
if (Event.current.Equals(Event.KeyboardEvent("return")))
print("I said enter, not return - try the keypad");
}
}
5.
Debug.Log((string)Input.inputString);
使用这个方法可以 返回 对应 按键 的小写 英文字母
只能检测 当前键盘 输入的字母 和数字,其他的按键 均返回 空null
Event.current.type
返回的是KeyDown和KeyUp
为什么会显示两次统一按键,因为Input.anyKeyDown和Input.anyKey函数,各调用一次
选择当Input.anyKeyDown或者Input.anyKey函数调用的时候,就运行一次代码
void OnGUI()//仅用作 响应 任意按键
{
Event e = Event.current;
//Debug.Log(Event.current.type);
if (AnyKeyControl_Bool)
{
if (e.isKey)
{
if (Input.anyKeyDown)
{
//清空按下帧数
keyFrame = 0;
Debug.Log("任意键被按下");
Debug.Log("Detected key code 1: " + e.keyCode);
}
if (Input.anyKey)
{
keyFrame++;
timeDelay+=Time.deltaTime;
TestAnyKey = e.keyCode;
Debug.Log("任意键被长按" + keyFrame + "帧");
Debug.Log("Detected key code 2: " + TestAnyKey);
Debug.Log("时间: " + timeDelay);
}
}
}
}
每一次按键 帧数 所花的时间 为0.02S,这一帧到下一帧调用的时间是0.02S
参考资料:
1.
unity3d 如何按下任意键输出那个键的代码
2.
unity3d输入与控制——键盘事件
3.
Unity在Editor下获取键盘等设备Input事件
4.
5.
6.
7.
8.
这篇博客介绍了在Unity中如何检测并输出任意按键的名称。通过使用Event类和Input类的方法,包括OnGUI事件、Event.current.isKey、Input.anyKeyDown和Input.anyKey,来实现对键盘事件的监听。文章详细讲解了不同方法的实现方式,并提供了代码示例,展示了在Unity编辑器环境下获取键盘输入事件的多种方法。
2727

被折叠的 条评论
为什么被折叠?



