回合制游戏中如何阻止方法记住变量的上一轮值?
回合制敌人攻击脚本延迟/状态残留问题修复
问题核心是Update函数每帧重复触发攻击协程,且回合结束后未及时重置状态,导致上一轮的攻击动作仍在执行。新回合生成的随机攻击值虽然正确,但旧协程的移动逻辑会先完成,才会执行新的攻击指令,最终出现“先按上一轮动作移动,再执行当前攻击”的延迟现象。
修复方案
- 触发攻击后立即关闭
enableAction开关,避免Update持续重复启动协程 - 回合开始时终止上一轮可能残留的协程,防止动作叠加冲突
- 回合结束时强制重置状态,杜绝跨回合的状态干扰
修改后的完整代码
private int randomAttack; private bool enableAction; // 保存当前运行的攻击协程,方便中途终止 private Coroutine currentAttackCoroutine; public void BeginTurn() { if (GameManagerPVE.instance.curPlayer == enemy) { // 先终止上一轮未完成的协程 if(currentAttackCoroutine != null) { StopCoroutine(currentAttackCoroutine); currentAttackCoroutine = null; } randomAttack = Random.Range(0, 2); // 生成0或1,替代原写法Random.Range(0,1+1) enableAction = true; } } IEnumerator EndTurn() { // 回合结束时重置所有状态 enableAction = false; if(currentAttackCoroutine != null) { StopCoroutine(currentAttackCoroutine); currentAttackCoroutine = null; } GameManagerPVE.instance.SetNextTurn(2); yield return null; } void Update() { if(enableAction) { // 执行一次攻击逻辑后立即关闭开关,避免每帧重复触发 enableAction = false; if(randomAttack == 0) currentAttackCoroutine = StartCoroutine(MeleeAttack()); else currentAttackCoroutine = StartCoroutine(RangeAttack()); } }
额外提示
- 确保
MeleeAttack()和RangeAttack()协程内部包含完整的流程:移动到目标位置→执行攻击→调用EndTurn()触发回合结束,避免状态卡住 - 如果移动或攻击逻辑中有异步等待(比如等待动画播放),要确保协程能正常执行到结尾,不会中途挂起
内容的提问来源于stack exchange,提问作者jsmith
相关产品推荐
相关产品推荐

