Skip to main content
ARShow
ARShow
 首页 » 资源教程

Unity3D捕获键盘数字键按键信息

2016年08月19日 18:07:2413070

我们需要捕获1-9这些数字,如果直接用GetKeyDown的话,需要这样写:

1
2
3
4
5
6
7
void OnGUI () {
for (int i = 0; a < 9; i++){
if(Input.GetKeyDown(KeyCode.Alpha[i])){
GUI.Box (new Rect (0,Screen.height - 50,100,50), "Item"+ i.ToString());
GUI.Box (new Rect (Screen.width/2,Screen.height/2,100,50), "Item"+ i.ToString()+1 );
GUI.Box (new Rect (Screen.width - 100,Screen.height - 50,100,50), "Item "+ i.ToString()+2);
}

但这不是最佳方案,我们可以使用Event来处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 没有数字键按下,为0
private int numDown;
  
void OnGUI() {
     // Render boxes if numeric key 1-9 is pressed.
     if (numDown != 0) {
         GUI.Box(
             new Rect(0, Screen.height - 50, 100, 50),
             "Item " + numDown
         );
         GUI.Box(
             new Rect(Screen.width/2, Screen.height/2, 100, 50),
             "Item " + (numDown + 1)
         );
         GUI.Box(
             new Rect(Screen.width - 100, Screen.height - 50, 100, 50),
             "Item " + (numDown + 2)
         );
     }
  
     // 处理键盘事件
     int num;
     if (Event.current.type == EventType.KeyDown) {
         // 为了方便,转换到数值
         num = Event.current.keyCode - KeyCode.Alpha1 + 1;
  
         // 避免多个数字键同时按下
         if (numDown == 0 && num >= 1 && num <= 9) {
             numDown = num;
             Event.current.Use();
         }
     }
     else if (Event.current.type == EventType.KeyUp) {
         num = Event.current.keyCode - KeyCode.Alpha1 + 1;
         if (numDown == num) {
             numDown = 0;
             Event.current.Use();
         }
     }
}


评论列表暂无评论
发表评论