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

能否通过脚本在运行时为不同对象设置Unity Input System交互的按住时长?

在Unity新版Input System中动态修改交互对象的按住时长

核心思路

针对每个交互对象配置独立的按住时长,在检测到目标交互对象时,动态修改Input Action中Hold Interaction的duration属性。

步骤1:给交互对象添加配置脚本

给需要自定义按住时长的对象挂载以下脚本,用于存储该对象所需的触发时长:

using UnityEngine;

public class InteractableObject : MonoBehaviour
{
    [Tooltip("触发该对象交互需要的按住时长(单位:秒)")]
    public float requiredHoldTime = 1f;
}

在Inspector面板中,给对象A设为1秒,对象B设为2秒即可。

步骤2:动态修改Hold Interaction的时长

在你的交互管理脚本中,找到Input Action对应的Hold Interaction实例,并根据当前选中的交互对象更新时长:

using UnityEngine;
using UnityEngine.InputSystem;

public class InteractionManager : MonoBehaviour
{
    // 拖拽绑定你的按住交互Input Action
    [SerializeField] private InputAction holdInteractAction;
    private HoldInteraction holdInteraction;

    private void Awake()
    {
        // 从Action的交互列表中定位到Hold类型的交互实例
        foreach (var interaction in holdInteractAction.interactions)
        {
            if (interaction is HoldInteraction hold)
            {
                holdInteraction = hold;
                break;
            }
        }
    }

    // 替换成你实际的交互对象检测逻辑(比如射线检测、碰撞体检测)
    private InteractableObject GetCurrentTargetInteractable()
    {
        // 示例:鼠标射线检测当前指向的交互对象
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out RaycastHit hitInfo))
        {
            return hitInfo.collider.GetComponent<InteractableObject>();
        }
        return null;
    }

    private void Update()
    {
        var targetInteractable = GetCurrentTargetInteractable();
        // 当检测到有效交互对象时,更新按住时长
        if (targetInteractable != null && holdInteraction != null)
        {
            holdInteraction.duration = targetInteractable.requiredHoldTime;
        }
    }
}

关键注意事项

  • 确保你的Input Action已经添加了Hold Interaction:在Input Action设置面板中,点击Add Interaction选择Hold
  • 修改时长的时机要提前:最好在用户开始按住操作前就完成时长更新(比如选中对象时),避免按住过程中修改导致的逻辑混乱
  • 如果Action包含多个Interaction,要精准筛选Hold类型的实例,避免误修改其他交互参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:45:11