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

Unity中如何实现按住E键3秒触发功能?脚本调试遇异常

解决Unity脚本中Timer始终为0的问题

问题根源

你的代码没有封装在Update()方法内,Unity无法每一帧检测Input.GetButtonDown("Fire2")的触发事件,导致timer从未被赋值,始终保持初始值0。

修正代码

float timer = 0;
float timerB = 0;

void Update()
{
    if (Input.GetButtonDown("Fire2"))
    {
        timer = Time.time;
        Debug.Log(timer);
    }

    if (Input.GetButtonUp("Fire2"))
    {
        timerB = Time.time;
        Debug.Log($"{timerB} ESPACIOSSS {timer}");
        if (timerB - timer >= 3)
        {
            timer = 0;
            timerB = 0;
            Debug.Log("CONSEGUIDOOOOOOOOOOOOOOOOOOOOOOOOOO");
        }
    }
}

关键说明

  • Unity的输入检测逻辑必须放在Update()这类帧循环方法中,因为该方法会在游戏运行时逐帧执行,才能实时响应用户的按键操作。
  • 这个场景不需要协程,协程多用于处理延迟执行、分帧完成的异步任务(比如等待3秒后触发事件),当前需求用帧循环检测即可满足。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:45:41