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

Unity中WaitForSeconds函数不生效,无法实现枪械射击冷却功能求助

问题原因
  • 现有代码没有冷却状态校验,每次点击鼠标都会独立启动一个ShootThenDelay协程,协程的等待逻辑不会阻止新的射击请求触发,所以可以无限制射击。
  • 协程的WaitForSeconds只是暂停当前协程的后续执行,不会阻塞Update函数的输入检测,也不会阻止其他协程启动。
修复方案

新增一个isCoolingDown的私有布尔变量标记冷却状态,射击后标记为冷却中,冷却结束后重置状态,只有非冷却状态下才响应射击输入。

修复后的完整代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GunController : MonoBehaviour
{
    public Transform firePoint;
    public GameObject bulletPrefab;
    public string gunType;
    // 新增冷却状态标记
    private bool isCoolingDown = false;

    private void Update()
    {
        // 只有不在冷却状态时才响应射击输入
        if (Input.GetMouseButtonDown(0) && !isCoolingDown)
        {
            switch (gunType)
            {
                case "pistol":
                    StartCoroutine(ShootThenDelay(0.5f));
                    break;
            }
        }
    }


    IEnumerator ShootThenDelay(float seconds)
    {
        // 进入冷却状态
        isCoolingDown = true;
        Shoot();
        yield return new WaitForSeconds(seconds);
        // 冷却结束重置状态
        isCoolingDown = false;
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
    }
}
改动说明
  • 新增私有变量isCoolingDown默认值为false,记录枪械是否处于冷却状态
  • 在Update的射击输入判断中新增!isCoolingDown条件,冷却状态下不响应射击
  • 在协程ShootThenDelay开头将isCoolingDown设为true,锁定射击权限
  • 协程等待0.5秒结束后将isCoolingDown重置为false,恢复射击权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:30:03