Unity中拖拽逻辑仅生效一次的问题求助
问题解决:Unity 6拖拽功能仅生效一次的修复
可能原因及对应方案
1. 新输入系统与OnMouse事件的兼容性问题
Unity 6默认启用新输入系统,OnMouseDown/OnMouseUp这类旧输入事件可能出现注册异常,可通过两种方式解决:
方案A:启用旧输入系统兼容
- 打开
Edit > Project Settings > Player - 在
Active Input Handling下拉菜单中选择Both或Old Input System - 重启Unity后测试
方案B:改用新输入系统实现拖拽
替换原有代码为新输入系统逻辑,彻底避免兼容性问题:
using UnityEngine; using UnityEngine.InputSystem; public class DragObject : MonoBehaviour { private Camera _camera; private bool _dragging; private Vector2 _mouseStartPos; private Vector3 _objectStartPos; private void Awake() { _camera = Camera.main; } private void OnEnable() { Mouse.current.leftButton.started += OnDragStart; Mouse.current.leftButton.canceled += OnDragEnd; } private void OnDisable() { Mouse.current.leftButton.started -= OnDragStart; Mouse.current.leftButton.canceled -= OnDragEnd; } private void Update() { if (_dragging) { Vector2 mouseWorldPos = _camera.ScreenToWorldPoint(Mouse.current.position.ReadValue()); transform.position = _objectStartPos + (Vector3)(mouseWorldPos - _mouseStartPos); } } private void OnDragStart(InputAction.CallbackContext context) { RaycastHit2D hit = Physics2D.Raycast(_camera.ScreenToWorldPoint(Mouse.current.position.ReadValue()), Vector2.zero); if (hit.collider != null && hit.collider.gameObject == gameObject) { _dragging = true; _mouseStartPos = Mouse.current.position.ReadValue(); _objectStartPos = transform.position; } } private void OnDragEnd(InputAction.CallbackContext context) { _dragging = false; } }
2. Collider2D状态异常
拖拽后Collider2D可能因物体位置变化丢失事件注册,可在拖拽结束时强制刷新:
private void OnMouseUp() { _dragging = false; // 强制重置Collider2D状态 var collider = GetComponent<Collider2D>(); collider.enabled = false; collider.enabled = true; }
注:此为临时修复方案,优先推荐输入系统相关解决路径。
3. Physics2D.autoSimulation设置位置
Unity 6中该选项路径为:Edit > Project Settings > Physics 2D,在Simulation分组下找到Auto Simulation,确保其处于勾选状态。若未勾选,物理系统会停止自动模拟,导致碰撞事件完全失效。
内容的提问来源于stack exchange,提问作者SoggyEyeball
相关产品推荐
相关产品推荐

