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

回合制游戏中如何阻止方法记住变量的上一轮值?

回合制敌人攻击脚本延迟/状态残留问题修复

问题核心是Update函数每帧重复触发攻击协程,且回合结束后未及时重置状态,导致上一轮的攻击动作仍在执行。新回合生成的随机攻击值虽然正确,但旧协程的移动逻辑会先完成,才会执行新的攻击指令,最终出现“先按上一轮动作移动,再执行当前攻击”的延迟现象。

修复方案

  1. 触发攻击后立即关闭enableAction开关,避免Update持续重复启动协程
  2. 回合开始时终止上一轮可能残留的协程,防止动作叠加冲突
  3. 回合结束时强制重置状态,杜绝跨回合的状态干扰

修改后的完整代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:22:41