提示:文章有错误的地方,还望诸位大神不吝指教!
官方文档Input System:链接: Input System
安装部分:链接: Unity XR Interaction Toolkit的安装(二)
需要导入官方案例:Starter Assets,方便学习
选择顺序 XR Controller–>XR Controller (RightHand)或者XR Controller(LeftHand)–>Usage
代码如下(示例):
using UnityEngine; using UnityEngine.InputSystem; namespace TWQ { public class MenuManage : MonoBehaviour { public InputActionReference MyLeftButton_X; public InputActionReference MyLeftButton_Y; public InputActionReference MyRightButton_X; public InputActionReference MyRightButton_Y; private void OnEnable() { SetupInteractorEvents(); } private void OnDisable() { TeardownInteractorEvents(); } void SetupInteractorEvents() { //左手 var MyLeftButton_X_Action = GetInputAction(MyLeftButton_X); if (MyLeftButton_X_Action != null) { MyLeftButton_X_Action.performed += OnMyLeftButton_X_Action; } var MyLeftButton_Y_Action = GetInputAction(MyLeftButton_Y); if (MyLeftButton_Y_Action != null) { MyLeftButton_Y_Action.performed += OnMyLeftButton_Y_Action; } //右手 var MyRightButton_X_Action = GetInputAction(MyRightButton_X); if (MyRightButton_X_Action != null) { MyRightButton_X_Action.performed += OnMyRightButton_X_Action; } var MyRightButton_Y_Action = GetInputAction(MyRightButton_Y); if (MyRightButton_Y_Action != null) { MyRightButton_Y_Action.performed += OnMyRightButton_Y_Action; } } void TeardownInteractorEvents() { var MyLeftButton_X_Action = GetInputAction(MyLeftButton_X); if (MyLeftButton_X_Action != null) { MyLeftButton_X_Action.performed -= OnMyLeftButton_X_Action; } var MyLeftButton_Y_Action = GetInputAction(MyLeftButton_Y); if (MyLeftButton_Y_Action != null) { MyLeftButton_Y_Action.performed -= OnMyLeftButton_Y_Action; } } /// /// 左手X键 /// /// private void OnMyLeftButton_X_Action(InputAction.CallbackContext context) { Debug.Log("按下左手X键--------------------"); } /// /// 左手Y键 /// /// private void OnMyLeftButton_Y_Action(InputAction.CallbackContext context) { Debug.Log("按下左手Y键--------------------"); } /// /// 右手X键 /// /// private void OnMyRightButton_X_Action(InputAction.CallbackContext context) { Debug.Log("按下右手A键--------------------"); } /// /// 右手Y键 /// /// private void OnMyRightButton_Y_Action(InputAction.CallbackContext context) { Debug.Log("按下右手B键--------------------"); } static InputAction GetInputAction(InputActionReference actionReference) { #pragma warning disable IDE0031 // Use null propagation -- Do not use for UnityEngine.Object types return actionReference != null ? actionReference.action : null; #pragma warning restore IDE0031 } } }
好记性不如烂笔头