- Home /
how to add to the waitforseconds of a qoroutine while it is already waiting?
hello, I have a complicated issue. I have a script that runs a coroutine that has a WaitForSeconds in it. when the player steps on a button, the script plays an animation, waits for five seconds, then plays another animation. the problem is, I want to be able to delay the second animation by stepping on another button. the issue is that even if I add to the amount that the WaitForSeconds is supposed to wait for, if the WaitForSeconds amount started waiting already, it will use the value it started with even if the amount it's supposed to wait for changes while it is waiting. is there a way to make the WaitForSeconds delay longer even after it has already started waiting?
Answer by ArtOfProgramming · Sep 05, 2021 at 07:31 AM
What I would do @WerewoofPrime is:
Option #1
- When the coroutine gets created store it into a variable.
Have a variable that stores the amount of time that has passed since the coroutine started
When the other button is pressed stop the previous coroutine and start a new one with a different WaitForSeconds time based upon the time that has passed of the previous coroutine.
Option #2:
- Don't work with coroutines but with the update in your game.
Have a time it starts from and count it down
When the player steps on the other button ad a fixed amount to the time variable that gets counted down.
Hope these options help you and good luck.
Yes either of these could work, but option 2 is better overall if you can I think. Just make sure to use FixedUpdate, not the regular Update loop that way you can actually control it without having to use Time.deltaTime.
Thank you! This looks like a good idea. Thank you for your answer!
I am so excited because you gave me a great idea!! thank you so much! I think this is going to work.
Answer by Hellium · Sep 05, 2021 at 07:47 AM
private float coroutineResumeTime;
private IEnumerator MyCoroutine()
{
// ...
coroutineResumeTime = Time.time + 5f;
yield return new WaitUntil(() => Time.time > coroutineResumeTime);
// ....
}
public void OnButtonPressed()
{
coroutineResumeTime += 10;
}
PS: Next time, please provide your code.
Thank you for answering me! I am sorry about not posting my code. If you want me to i still can.
Answer by Bonfire-Boy · Sep 07, 2021 at 11:55 AM
I just wouldn't use WaitForSeconds here. You can manage the waiting yourself....
float waitDuration = 10f;
// instead of yield return new WaitForSeconds(waitDuration);
IEnumerator CR()
{
float elapsed = 0f;
while (elapsed < waitDuration)
{
elapsed += Time.deltaTime;
yield return null;
}
}
Now you can change the wait time while waiting, just by changing the value of waitDuration
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
adding a delay to shooting 2 Answers
How do I implement delays in my code? 3 Answers
Why does my particle system get enabled with a delay? 2 Answers