Unity中使用Time.deltaTime递减float变量数值不下降问题咨询
问题原因
你每帧在Update中调用StopAllPlayerControl(3)时,方法第一行stopPlayerDuration = duration会直接把计时变量重置为3,之后仅减去极小的Time.deltaTime,下帧又会被重新赋值为3,所以数值始终维持在接近3的水平,不会出现持续递减的效果。
修复方案
你需要把「触发暂停」和「计时更新」的逻辑拆分,不要把计时逻辑放在触发暂停的方法里重复执行:
- 新增一个布尔变量标记当前是否处于暂停计时状态:
private bool isStoppingPlayer = false; - 单独写触发暂停的方法,仅在需要开启暂停时调用一次,无需每帧调用
- 计时递减逻辑单独放在
Update中,仅在暂停状态激活时执行
代码示例
// 触发暂停的方法,需要暂停时调用一次即可 public void TriggerStopPlayerControl(float duration) { stopPlayerDuration = duration; isStoppingPlayer = true; playerInput.enableMovement = false; } private void Update() { // 仅在暂停计时状态下执行递减判断 if (isStoppingPlayer) { stopPlayerDuration -= Time.deltaTime; if (stopPlayerDuration <= 0) { // 计时结束恢复控制 playerInput.enableMovement = true; isStoppingPlayer = false; } } // 其余原有Update逻辑 // 触发暂停示例:对应条件满足时调用一次即可,不要每帧执行 // if (触发暂停的条件) // { // TriggerStopPlayerControl(3); // } }
内容的提问来源于stack exchange,提问作者gonzalo carrasco
相关产品推荐
相关产品推荐

