Unity2D射击延迟功能异常:Debug正常但无法生成子弹
Unity2D射击延迟功能失效修复
问题描述
在Unity2D游戏中添加射击延迟冷却功能时,采用currentime += Time.deltaTime实现时间累加,Debug.Log显示时间逻辑正常,但子弹始终无法生成,Hierarchy面板中无子弹实例,排除位置问题。
原代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class shoot : MonoBehaviour { public GameObject bullet; public float delay = 3f; public float currentime = 0; void Start() { } void Update() { Debug.Log(currentime); currentime += Time.deltaTime; if (Input.GetMouseButton(0)) { if (currentime > delay) { currentime = 0; Instantiate(bullet, transform.position, Quaternion.identity); } } } }
问题原因
- 输入检测逻辑错误:
Input.GetMouseButton(0)仅在鼠标左键持续按住时返回true,若用户仅点击一下(按下即松开),按下帧内currentime大概率未累加至delay阈值,无法触发射击;即使等待足够冷却时间后点击,松开鼠标后也不会触发检测。 - 时间输出与逻辑不同步:先执行
Debug.Log(currentime)再累加时间,日志显示的是上一帧的时间值,与当前帧用于判断冷却的时间不一致,易造成调试误解。
修复方案
修改输入检测为鼠标按下瞬间触发,并调整时间累加与日志输出的顺序:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class shoot : MonoBehaviour { public GameObject bullet; public float delay = 3f; public float currentime = 0; void Start() { } void Update() { currentime += Time.deltaTime; Debug.Log(currentime); // 先累加再输出,确保日志与判断逻辑同步 // 检测鼠标左键按下的瞬间 if (Input.GetMouseButtonDown(0)) { if (currentime > delay) { currentime = 0; Instantiate(bullet, transform.position, Quaternion.identity); } } } }
额外检查项
- 确认
bullet字段已在Inspector面板中正确拖入预制体资源。 - 若需要持续按住鼠标实现连射(需满足冷却间隔),可保留
Input.GetMouseButton(0),但需确保等待足够冷却时间后再按住鼠标,或调整delay值测试。
内容的提问来源于stack exchange,提问作者Dylan Santwani
相关产品推荐
相关产品推荐

