【长按短按】Unity输入系统模块

寒假在做Unity小项目时,想实现一个功能:单击shift键角色冲刺、长按shift键角色疾跑,于是需要处理长按和短按的问题。在互联网上找的教程,要么是针对于老输入系统的——麻烦、代码量繁杂。要么是针对新输入系统、但不易理解、代码冗杂。于是这里分享一套自己的框架,用起来还是很顺手的,巧妙处理长按、短按。

思路介绍

图片 我们安装新的输入系统后,创建一个输入文件、一个GameInputManager类,使用继承MonoBehaviour的单例模式基类,OnEnable时启用、OnDisable时关闭。在输入配置文件里,创建两个键位,给Sprint和Fast_Run都绑定左shift键,前者interactions添加一个tap,后者则是添加Hold。于是就有了以下代码:
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Interactions;

public class GameInputManager : MonoSingle<GameInputManager>
{
private GameInputAction _gameInputAction;
//书写按键逻辑
public Vector2 movement => _gameInputAction.GameInput.Move.ReadValue<Vector2>();
//锁敌
private bool _lock = false;
//贴墙
private bool _wall = false;
//切武器
private bool _weapon = false;
public bool Lock
{
get
{
if (_gameInputAction.GameInput.Lock.triggered)
_lock = !_lock;
return _lock;

}
}
//格挡
public bool Parry => _gameInputAction.GameInput.Parry.IsPressed();
// 冲刺
public bool Sprint => _gameInputAction.GameInput.Sprint.triggered;

// 疾跑
public bool Fast_Run => _gameInputAction.GameInput.Fast_Run.IsPressed();
//攻击
public bool LeftAttack => _gameInputAction.GameInput.LeftAttack.triggered;
public bool RightAttack => _gameInputAction.GameInput.RightAttack.triggered;

//相机
public Vector2 Camera => _gameInputAction.GameInput.Camera.ReadValue<Vector2>();
//技能
public bool Ctrl => _gameInputAction.GameInput.Ctrl.triggered;
public bool Q => _gameInputAction.GameInput.Q.triggered;
//切换技能
public bool Z => _gameInputAction.GameInput.Q.triggered;
//贴墙
public bool X
{
get
{
if (_gameInputAction.GameInput.Lock.triggered)
_wall = !_wall;
return _wall;
}
}

//切换武器

public bool Tab
{
get
{
if (_gameInputAction.GameInput.Tab.triggered)
_weapon = !_weapon;
return _weapon;
}
}


private void OnEnable()
{
_gameInputAction ??= new GameInputAction();
_gameInputAction.Enable();
}

private void OnDisable()
{
_gameInputAction.Disable();
}
}