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

Unity中使用协程实现换弹冷却的方式是否有误?

解决Unity枪械换弹协程无等待效果问题

问题根源

你的代码里协程仅执行了WaitForSeconds等待,但没有添加换弹状态锁阻止后续射击触发逻辑。启动协程后玩家仍能通过鼠标点击触发射击判断,因此看起来没有等待效果。

修复方案

  1. 添加布尔变量标记换弹状态
  2. 在射击判断条件中加入换弹状态检查
  3. 修改协程逻辑,换弹期间锁定射击,等待结束后解锁

修改后的完整代码示例

首先声明换弹状态变量:

private bool isReloading = false;

更新射击判断逻辑:

if (Input.GetMouseButton(0) && Time.time > nextFire && !inventoryInterface.activeSelf && !isReloading)
{
    //aimAnimator.SetTrigger("Shoot");
    nextFire = Time.time + fireRate;
    if (count < gun.bulletsInAMagazine)
    {
        Vector3 mousePosition = UtilsClass.GetMouseWorldPosition();
        OnShoot?.Invoke(this, new OnShootEventArgs
        {
            gunEndPointPosition = aimGunEndPointPosition.position,
            shootPosition = mousePosition
        });
        count++;
    }
    else
    {
        count = 0;
        StartCoroutine(FireCooldown());
        Debug.Log("Reloading");
    }
}

修改协程逻辑:

IEnumerator FireCooldown()
{
    isReloading = true;
    // 可在此添加换弹动画播放、音效等逻辑
    yield return new WaitForSeconds(gun.reloadTime);
    isReloading = false;
    // 可选:换弹完成后重置射击间隔,避免立刻触发射击
    nextFire = Time.time + fireRate;
}

原理说明

通过isReloading变量,启动换弹协程时将其设为true,此时射击判断条件中的!isReloading会阻止后续射击触发。协程等待gun.reloadTime时长后,再将isReloading设为false恢复射击功能,从而实现真正的换弹冷却效果。

内容的提问来源于stack exchange,提问作者Thành Vinh Ninh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:25:21