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

Unity3d中如何用C#检测按键是否被按住2秒?

Unity C# 检测按键持续按住2秒的实现方法

基础实现(Update帧循环处理)

最直接的方式是在Update里跟踪按键的按住时长,当按键持续按住达到2秒时触发目标逻辑:

using UnityEngine;

public class KeyHoldChecker : MonoBehaviour
{
    // 可在Inspector面板指定要检测的按键
    public KeyCode targetKey = KeyCode.LeftShift;
    // 触发逻辑所需的按住时长
    private readonly float requiredHoldTime = 2f;
    // 当前累计的按住时间
    private float currentHoldDuration = 0f;
    // 标记是否已触发过逻辑,避免重复执行
    private bool hasTriggered = false;

    void Update()
    {
        if (Input.GetKey(targetKey))
        {
            // 累加每帧的时间增量,计算准确的按住时长
            currentHoldDuration += Time.deltaTime;

            // 达到时长且未触发过逻辑时执行操作
            if (currentHoldDuration >= requiredHoldTime && !hasTriggered)
            {
                TriggerHoldAction();
                hasTriggered = true;
            }
        }
        else
        {
            // 按键抬起时重置计时器和触发标记
            currentHoldDuration = 0f;
            hasTriggered = false;
        }
    }

    // 按键按住足够时长后执行的自定义逻辑
    private void TriggerHoldAction()
    {
        Debug.Log($"按键 {targetKey} 已持续按住2秒!");
        // 在这里添加你的游戏逻辑:比如打开技能面板、触发蓄力效果等
    }
}

协程实现(非帧循环方式)

如果不想在Update里堆积逻辑,可以用协程实现,仅在按键按下时启动检测:

using UnityEngine;
using System.Collections;

public class KeyHoldCoroutineChecker : MonoBehaviour
{
    public KeyCode targetKey = KeyCode.LeftShift;
    // 标记协程是否正在运行,避免重复启动
    private bool isChecking = false;

    void Update()
    {
        // 按键按下瞬间启动协程
        if (Input.GetKeyDown(targetKey) && !isChecking)
        {
            StartCoroutine(VerifyHoldDuration());
        }

        // 按键抬起时终止检测
        if (Input.GetKeyUp(targetKey))
        {
            isChecking = false;
        }
    }

    IEnumerator VerifyHoldDuration()
    {
        isChecking = true;
        // 等待2秒
        yield return new WaitForSeconds(2f);

        // 等待结束后再次确认按键是否仍被按住
        if (Input.GetKey(targetKey))
        {
            TriggerHoldAction();
        }

        isChecking = false;
    }

    private void TriggerHoldAction()
    {
        Debug.Log($"按键 {targetKey} 已持续按住2秒!");
        // 自定义逻辑代码
    }
}

关键注意点

  • Input.GetKey:持续检测按键状态,和仅检测按下瞬间的Input.GetKeyDown、检测抬起瞬间的Input.GetKeyUp区分开。
  • Time.deltaTime:保证跨帧率的时间计算准确,避免因帧率波动导致计时偏差。
  • 触发标记:防止在按键持续按住期间重复执行目标逻辑,只有当按键抬起后再次按住才会重新触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 21:34:51