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
相关产品推荐
相关产品推荐

