Unity新输入系统.started事件失效,.performed单次点击触发两次问题
Unity New Input System鼠标点击事件触发异常解决方案
问题根源
事件触发异常是因为Input Action的交互配置错误:
- 默认无自定义交互的
Button类型动作,.performed事件会在按下、释放两个节点各触发一次,所以单次点击会调用两次回调 .started、.canceled无响应是因为缺少Press交互,默认动作不会触发这两个阶段的事件
解决步骤
- 打开你项目中的Input Action资产文件,定位到
Gameplay分组下的Shoot动作 - 确认动作的
Action Type属性设置为Button - 点击
Shoot动作右侧的「+」按钮,添加Press交互 - 将新增的
Press交互的Trigger Behavior属性设置为Press And Release
代码优化
private void OnEnable() { controls.Gameplay.Shoot.started += PlayerAimingStart; controls.Gameplay.Shoot.performed += PlayerAimingPerformed; } // 必须新增取消订阅逻辑,避免内存泄漏 private void OnDisable() { controls.Gameplay.Shoot.started -= PlayerAimingStart; controls.Gameplay.Shoot.performed -= PlayerAimingPerformed; } private void PlayerAimingStart(InputAction.CallbackContext ctx) { shootingPositionStart = controls.Gameplay.MousePosition.ReadValue<Vector2>(); shootingPositionStart.z = 0f; } private void PlayerAimingPerformed(InputAction.CallbackContext ctx) { // 增加判空逻辑避免未按下就触发的异常 if(shootingPositionStart == Vector3.zero) return; shootingPositionEnd = controls.Gameplay.MousePosition.ReadValue<Vector2>(); shootingPositionEnd.z = 0f; Vector3 force = shootingPositionStart - shootingPositionEnd; Vector3 clampedForce = Vector3.ClampMagnitude(force, maxDrag) * power; bulletGO.GetComponent<Rigidbody2D>().AddForce(clampedForce, ForceMode2D.Impulse); // 重置起始位置避免下次点击复用旧值 shootingPositionStart = Vector3.zero; }
可选优化
如果不需要全局统一管理鼠标位置,你可以直接用Mouse.current.position.ReadValue<Vector2>()读取当前鼠标坐标,无需在Input Map中单独定义MousePosition动作。
内容的提问来源于stack exchange,提问作者Ciejkee
相关产品推荐
相关产品推荐

