- Home /
Need to make synchronous delay function (not running in parallel like coroutine or Invoke)
This Delay function I wrote is called after a button is pressed. When it runs, Unity crashes and doesn't even print the debug statement inside the while loop:
private bool delayOver;
public void Delay(float seconds)
{
delayOver = false;
StartCoroutine(DelayCoroutine(seconds));
while(!delayOver)
{
Debug.Log("in loop...");
}
Debug.Log("delay is over, do next thing");
}
private IEnumerator DelayCoroutine(float seconds)
{
yield return new WaitForSeconds(seconds);
delayOver = true;
}
Note: I am familiar with coroutines and the Invoke function, I have used both of them in the conventional way in games I've made. In this case I need to do it differently, like the code above, without it crashing.
Answer by lmartinignacio · Mar 31 at 05:28 AM
I think you should not block the main thread with a while loop.
private IEnumerator DelayCoroutine(float seconds)
{
Debug.Log("Before waiting"); //here you have what you want to execute before waiting
yield return new WaitForSeconds(seconds);
Debug.Log("delay is over"); //Here you have what should be executed after waiting.
}
If I do it that way, then any code after the coroutine call will run in parallel with the coroutine, and I can't have that. I want to block the main thread. If that's not possible, then I'll have to try something else, but I want to know how I can make a synchronous delay.
Your answer

Follow this Question
Related Questions
Unity Network Transform delay 1 Answer
Trying to add a delay to this script 1 Answer
Jump problem (2D) 0 Answers
Better way to delay a function for a few seconds? Javascript 1 Answer