You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity 3D交互系统故障:选中状态异常问题求助

Unity操作台交互系统异常排查与修复

问题现象

  • 首次选中操作台后,即使视线移开或距离过远,选中状态仍持续
  • 再次看向操作台时,选中状态可能失效

核心问题定位

1. HandleInteractions函数逻辑错误

射线检测命中ClearCounter的分支中,判断逻辑完全写反:当命中的操作台与当前选中对象相同时,错误调用SetSelectedCounter(null)取消选中;同时未命中物体的分支被遗漏,导致选中状态无法正常取消。

2. lastInteractDir的方向逻辑偏差

仅在玩家移动时更新交互方向,停止移动后会保留最后一次移动方向,导致射线始终沿旧方向发射,与玩家实际"看向"的方向不符。


修复后的代码实现

1. 修正交互处理函数

private void HandleInteractions()
{
    Vector2 inputVector = gameInput.GameMovementVectorNormalized();
    Vector3 movDir = new Vector3(inputVector.x, 0f, inputVector.y);

    // 修正交互方向:移动时用输入方向,静止时用玩家自身前方向(匹配"看向"逻辑)
    if (movDir != Vector3.zero)
    {
        lastInteractDir = movDir;
    }
    else
    {
        lastInteractDir = transform.forward;
    }

    float interactDistance = 1f;
    bool hitValidCounter = Physics.Raycast(transform.position, lastInteractDir, out RaycastHit raycastHit, interactDistance, countersLayerMask);

    if (hitValidCounter && raycastHit.transform.TryGetComponent(out ClearCounter clearCounter))
    {
        // 仅在选中对象变化时更新状态
        if (clearCounter != selectedCounter)
        {
            SetSelectedCounter(clearCounter);
        }
    }
    else
    {
        // 未命中有效操作台时,取消选中
        if (selectedCounter != null)
        {
            SetSelectedCounter(null);
        }
    }
}

2. 保留正确的选中状态设置函数

private void SetSelectedCounter(ClearCounter selectedCounter)
{
    this.selectedCounter = selectedCounter;
    onSelectedCounterChanged?.Invoke(this, new onSelectedCounterChangedEventArgs
    {
        selectedCounter = selectedCounter
    });
}

public event EventHandler<onSelectedCounterChangedEventArgs> onSelectedCounterChanged;
public class onSelectedCounterChangedEventArgs : EventArgs
{
    public ClearCounter selectedCounter;
}

3. 状态处理与交互触发函数(原逻辑可保留)

// 交互触发
private void GameInput_OnInteractAction(object sender, System.EventArgs e)
{
    selectedCounter?.Interact();
}

// 操作台状态监听
private void Start()
{
    Player.Instance.onSelectedCounterChanged += Player_onSelectedCounterChanged;
}

private void Player_onSelectedCounterChanged(object sender, Player.onSelectedCounterChangedEventArgs e)
{
    visualGameObject.SetActive(e.selectedCounter == clearCounter);
}

// 交互日志
public void Interact()
{
    Debug.Log("Interact!");
}

修复说明

  1. 射线方向修正:静止时改用玩家自身前方向发射射线,确保射线始终指向玩家当前视线方向,而非最后一次移动方向。
  2. 逻辑分支修正:统一处理未命中场景,确保视线移开时能正常取消选中;命中相同操作台时保持选中状态,避免误取消。
  3. 代码简化:合并Show()/Hide()逻辑,用一行代码实现状态切换,提升可读性。

内容的提问来源于stack exchange,提问作者USMAN GHAUSE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 04:56:39