Unity Input开发日志 01

Unity #Unity

Input System 和 Input Manager

Input System是新一代的输入方案,相比于Input Manager,它更加灵活与强大,但是因为坑很多所以大厂还是在用Input Manager

不过Input System确实是处理了很多独立开发者在进行输入控制时可能遇到的痛点,所以还是值得推荐的,至少它不像Addressable那样只有坑,没有好处。

安装Input System

在Unity引擎中选中工具栏中的Window -> Package Manager,然后在搜索栏中输入Input System并安装。

然后我们需要在Project Settings中激活Input System,在Project Settings中选择Player -> Other Settings -> Active Input Handling -> Input System Package (New)

使用Input System

要使用Input System,我们需要先创建一个Input Action

在这个Input Action里创建一个Action Map,然后在这个Action Map里创建Action,每个Action代表一个输入设备上的一个输入事件。

在Inspector中我们让Input Action创建C#类,这样我们就可以在代码中使用这个Input Action

假设我们有一个叫作PlayerInputActionsInput Action,我们可以在代码中这样使用它:

PlayerInputActions inputActions = new PlayerInputActions();
var variable = inputActions.Player.Move.ReadValue<Vector2>();

上面的代码中PlayerInputActions是C#类名,PlayerAction Map名,MoveAction名,我们可以在Input Action的Inspector中设置每个Action的Control Type以控制它的输入使用的类型,然后用ReadValue<type>()方法来读取输入事件的值。

Player Input + EventSystem

我们可以通过Player Input组件来绑定Action,然后通过EventSystem来处理输入事件,可以实现更加灵活的输入处理。但需要注意的是EventSystemInput SystemInput Manager的不同,比如我们需要先Disable后再EnableEventSystem的实例,才能手动更改EventSystemcurrentSelectedGameObject,如下:

EventSystem eventSystem = EventSystem.current;
eventSystem.enabled = false;
eventSystem.currentSelectedGameObject = null;
eventSystem.currentSelectedGameObject = targetGameObject;
eventSystem.enabled = true;

否则会遇上将currentSelectedGameObject改为某个Button时会调用其OnClick方法等问题。

总结

Input System是Unity引擎中新的输入方案,相比于Input Manager,它更加灵活与强大,但它也存在很多问题,如果不是必要,还是不要用它。