Keyboard
helloz 4/3/2024 Unity3d
link
https://docs.unity3d.com/ScriptReference/KeyCode.html (opens new window)
Capture keyboard key event
Method 1
Get keyboard keys through events to avoid detection per frame
Complete button push, only do it once per frame, if there is no monitoring, do not do any message push
Method 2 ( UnityEngine.Input.GetKeyDown)
means that each script is detected in the update, which is not friendly
方法1
通过事件获取键盘按键,避免每帧检测
完成按键推送,每帧只做一次,如果没有监听,不做任何消息推送
方式2,
意味着每个脚本都在update中做检测,这是不友好的
eventType | Combining 'keyboard' and UnityEngine.Keycode value 'keyboard.Space' 'keyboard.A' 'keyboard.B' |
example
--method 1
function Start()
luaEvent:AddEventListener('keyboard.Space',this,OnKeyDown)
end
function OnKeyDown(info)
print("method 1: Down Space")
end
function OnDestroy()
luaEvent:RemoveEventListener('keyboard.Space',this)
end
--method 2
function Update()
if UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.Space) then
print("method 2: Down Space")
end
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
--close ui & set renderscale
scene id:761 、779
--隐藏UI
local record=newList(UnityEngine.GameObject)
local isShowUI =true
function Start()
FindCanvas()
luaEvent:AddEventListener('keyboard.V',this,OnKeyDownV)
luaEvent:AddEventListener('keyboard.B',this,OnKeyDownB)
end
function OnKeyDownB(info)
print("method 1: Down V")
local tab= GetTable('testRenderScale')
print(tab)
if tab then
tab.ShowOrHide()
end
end
function OnKeyDownV(info)
print("method 1: Down B")
if isShowUI then
isShowUI =false
else
isShowUI =true
end
SetUIState(isShowUI)
end
function FindCanvas()
local objs= GameObject.FindObjectsOfType(typeof(UnityEngine.Canvas))
for i = 0, objs.Length-1 do
--print(objs[i].name)
local canvas = objs[i]
local pName = canvas.transform.parent.name
if pName ~='InputManager' and pName ~='Fps' then
record:Add(canvas.gameObject)
end
end
end
function SetUIState(isShow)
for i = 0, record.Count-1 do
record[i]:SetActive(isShow)
end
end
function OnDestroy()
luaEvent:RemoveEventListener('keyboard.V',this)
luaEvent:RemoveEventListener('keyboard.B',this)
end
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
41
42
43
44
45
46
47
48
49
50
51
52
53
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
41
42
43
44
45
46
47
48
49
50
51
52
53