Input System 使用
Window 》Package Manager 》Input System 安装
Edit 》Project Settings 》Player 》 确保 Active Input Handling 选的是 Input System Package (New)
这个时候 Console 可能会报错了,因为我们已经决定了用新的 input。 正式来尝试使用 Input System.
首先 Window | Analysis | Input Debugger,可以看到它会有 Devices,甚至你可以尝试插一个手柄,它也会识别,你可以点击设备,然后就可以看相应的设备,比如点击 keyboard,然后尝试按键,可以看到一些信息。
Assets 右键Create 》Input Action,命名称为 PlayerControls
双击打开 PlayerControls,新建 Action Maps,命名 Player,然后新建 Jump
Jump 点击加号, 绑一下 Space 按键, 再加一个 绑定 j key
甚至如果你想,可以绑手柄上的按键,保存
在 PlayerControls 的 Inspector 中 Generate C# Class,它自动帮我们产生一个一个 C# 文件
修改之前的脚本:
using UnityEngine;
using UnityEngine.InputSystem;
public class UserInput : MonoBehaviour{
public PlayerControls playerControls;
private void Awake() {
playerControls = new PlayerControls();
}
private void OnEnable() {
playerControls.Enable();
}
private void OnDisable() {
playerControls.Disable();
}
void Start() {
playerControls.Player.Jump.performed += OnJump;
}
private void OnJump(InputAction.CallbackContext context) {
Debug.Log("Jump");
}
}
run, 点击 space 或者 j 建,都可以看到 Jump 被成功打印出来。
现在来分析代码:
Awake 中的代码是建立了一个 PlayerControls 的实例,这可以 refer 到我们刚刚定义的 Input Action
Enable/Disable 常规代码
Start 中的代码比较关键,我们通过 playerControls. 记得我们刚刚定义的 Action Maps 叫 Player,然后有一个 Action 叫 Jump,这里 playerControls.Player.Jump.performed += OnJump; 就是是把 OnJump 这个函数加到了它的 performed callback 中
事件触发: 点击 space 或者 j 键的时候就调用了 OnJump
Input System 的 Quick start guide 也提供了比如别的方法来 Invoke Unity 事件。
我也有看到过不生成 PlayerControls.cs 然后直接用代码 [SerializeField] InputActionReference gripInputAction; 直接去链接 InputAction 的。 当然官方文档中也提供了别的设置 Input Actions 的方法。
这里可以提到的是绕了一大圈之后, XR Interactive Toolkit 设计 Action Based Rig 这件事以及其中涉及的代码部分希望不要再让人那么迷茫了。甚至你可以给自己一点挑战,那就是不创建 C# class,直接代码设置 [SerializeField] InputActionReference gripInputAction;, inspector 中设置这个 gripInputAction,然后让 VR 手柄用另一种方式跟你说 Hello World。