- Home /
Other
Add delay in while loop
I am using a while loop and i want delay inside it. I have used coroutines and also async function with await Task.Delay()
But problem is that during delay they start executing other things which I don't want .I want a delay inside that while loop and the controller should be there during delay or wait , Should not get out and start execute other code.
Can you explain the reason you want this kind of delay? Whatever you run inside the while loop will be run until exited. If the looping takes long time this will basically halt the game since the main thread would be running only your loop. With coroutines you can prevent this from happening. If you just want the game "paused" then set Time.timeScale to 0. Anyway if you really want your game jammed for certain period of time the easy way is just to do it with Thread.Sleep(milliseconds);
Answer by SaveTheWorldDotGames · Nov 03, 2020 at 01:08 PM
Here's the line from the following example you'll need: yield return new WaitForSeconds(5);
This waits for 5 seconds, then continues on. I use it in my games to get a delay in the script code execution like you're wanting.
using UnityEngine;
using System.Collections;
public class WaitForSecondsExample : MonoBehaviour
{
void Start()
{
//Start the coroutine we define below named ExampleCoroutine.
StartCoroutine(ExampleCoroutine());
}
IEnumerator ExampleCoroutine()
{
//Print the time of when the function is first called.
Debug.Log("Started Coroutine at timestamp : " + Time.time);
//yield on a new YieldInstruction that waits for 5 seconds.
yield return new WaitForSeconds(5);
//After we have waited 5 seconds print the time again.
Debug.Log("Finished Coroutine at timestamp : " + Time.time);
}
}
Credit: https://docs.unity3d.com/ScriptReference/WaitForSeconds.html
Keep on Creating!
Justin of JustinTime Studios http://unity3d.expert
aqeel25 said that coroutine kind of behavior is not wanted here... What was asked was delay where nothing else is executed.. no idea why this would be needed.. but that was the question I think.. so halting the main thread with Thread.Sleep(milliseconds);
should do the trick.
Follow this Question
Related Questions
C# simple delay execution without coroutine? 2 Answers
Multiple Cars not working 1 Answer
Function delay? 1 Answer
Distribute terrain in zones 3 Answers