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

