Problem with coroutine waiting
Hey,
So I am trying to build a turn based strategy game. My problem is within the enemy turn, I want the player to see the individual moves by the enemies (one space at a time). So if an enemy moves 2 spaces per turn then the player will see the enemy move one space then the enemy waits and then moves again. Then the code moves on to the next enemy and will move the same way, one space, wait, move, etc. I will be having enemies that all move different total amounts.
The problem is that the enemyTurn function is called by the update method (as that is how i am dealing with what turn it currently is). Calling coroutines from update i have read creates multiple instances which is causing the problem. I saw someone post something similar to this and someone answered with invokeReapeating on the function call but as i will have varied number of enemies with varied maxMoves I feel that wouldn't work in my game. So how do i get a couroutine to wait between individual moves when it is being called by the update function?
IEnumerator enemyTurn() {
for(int i = 0; i < enemies.Length; i++) {
enemy currentEnemy = enemies[i].GetComponent<unit>();
for(int j = 0; j < currentEnemy.maxMoves; j++) {
currentEnemy.move(new Vector2(0, -1));
yield return new WaitForSeconds(1f); //Wait between individual moves
}
}
newTurn();
state = battleState.PLAYERTURN;
yield return new WaitForSeconds(2f); //Wait a little while before moving to playerTurn
}
p.s: As I have not built any form of AI yet, I am just getting the enemies to move arbitrarily downwards
You probably want some sort of game state machine where this coroutine is called just once at the relevant point (eg on enemy turn) then waits for it to end.
Your answer

Follow this Question
Related Questions
Is there a way to check something every frame from within a coroutine? 1 Answer
Tracking Turns in Turn Based Game Loop 1 Answer
coroutine or update for powerups cooldown 0 Answers
StartCoroutine_Auto_Internal can only be called from the main thread. 0 Answers
What is the best way to loop with very short and accurate interval? 0 Answers