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

Unity C#协程中WaitForSeconds后代码无法执行问题求助

2D回合制战斗游戏协程WaitForSeconds失效排查

我正在开发一款2D回合制战斗游戏,其中BattleStart协程用于支持多种敌人类型的战斗初始化。代码中TimerManager.StartToPlayer是值为2的float变量,通过Debug.Log已确认能正常读取该值,但执行到yield return new WaitForSeconds(TimerManager.StartToPlayer)后,后续启动PlayerTurn协程、Debug.Log等代码完全无法执行。

已排除以下可能性:

  • 游戏未崩溃,Time.timeScale值为1
  • 非Unity编辑器问题(新建项目重复复现了该异常)
  • 非嵌套协程问题(移除StartCoroutine(PlayerTurn())后异常依旧存在)
  • 挂载该脚本的GameObject未被禁用或销毁

奇怪的是,当移除Battle.SetActive(true)和实例化玩家、敌人UI预制体的代码后,WaitForSeconds能恢复正常工作。

相关代码如下:

public IEnumerator BattleStart(string toucher, string touched, Unitdetails playerStatsScript, Unitdetails enemyStatsScript)
{
    //Accumulating values
    playerStats = playerStatsScript;
    enemyStats = enemyStatsScript;
    Debug.Log(playerStats.unitName + " vs " + enemyStats.unitName);

    //setting up battle and GUI
    battleState = whoseTurn.Start;
    DialogueText.text = "You encountered " + enemyStats.unitName + ".";
    World.SetActive(false);
    Battle.SetActive(true);
    //Adding the player and enemy, placed as UI.
    GameObject playerPrefab = Instantiate(NametoObject[playerStatsScript.unitName], playerPos, Quaternion.identity);
    GameObject enemyPrefab = Instantiate(NametoObject[enemyStatsScript.unitName], enemyPos, Quaternion.identity);
    Debug.Log("This area of code reached. StartToPlayer:  " + TimerManager.StartToPlayer);

    yield return new WaitForSeconds(TimerManager.StartToPlayer);
    //note that we need this WaitForSeconds to exist. We are making this a regular method to focus on other errors.
    StartCoroutine(PlayerTurn());
    Debug.Log("This area of code reached.");
}

内容的提问来源于stack exchange,提问作者COO

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 12:02:09