- Home /
c# - Having problems with the WaitForSeconds() method.
I am currently making a poker game and want to add a 2 second delay between the bot decisions. The script works fine without the delay, but it is instant so the player can't process it. When I add the delay, the method only executes once. I'm guessing it has something to do with the StartCoroutine() being in a loop. Couldn't find anything else online. Any suggestions? Thank you.
PS: The variables references aren't accurate since they are from other parts of the code and the program works fine with the method being a void and referencing it normally.
The code:
public int current_bot;
public IEnumerator bot_phase_1(int current_bot)
{
yield return new WaitForSeconds(2f);
//the code
}
public void Button1()
{
//some code
while(bot_count>0)
{
StartCoroutine(bot_phase_1(current_bot));
assist--;
}
}
Answer by Namey5 · Jul 20, 2020 at 10:37 AM
You would want the loop to be within the coroutine - normal code won't wait for the coroutine to finish, so what ends up happening here is the loop runs through everything at once, and the coroutine is called multiple times simultaneously. Instead, you would probably want to do something like;
public IEnumerator bot_phase_1 (int current_bot)
{
while (bot_count > 0)
{
yield return new WaitForSeconds (2f);
assist--;
}
}
public void Button1 ()
{
StartCoroutine (bot_phase_1 (current_bot));
}
Assuming that you would fill in the logic to make this compile in your context, mind you.
Your answer
Follow this Question
Related Questions
WaitforSeconds woes 3 Answers
c# waitforsecconds 2 Answers
Pause script until animation is finished. 1 Answer
Problem with using IEnumerator for method, c# 1 Answer
Loop with WaitForSeconds in IEnumerator appears to be incorrect by 10-15% 2 Answers