How to Make the Script Wait/Sleep in a Simple Way in Unity

How to make the script wait/sleep in a simple way in unity

There are many ways to wait in Unity. They are really simple but I think it's worth covering most ways to do it:

1.With a coroutine and WaitForSeconds.

This is by far the simplest way. Put all the code that you need to wait for some time in a coroutine function then you can wait with WaitForSeconds. Note that in coroutine function, you call the function with StartCoroutine(yourFunction).

Example below will rotate 90 deg, wait for 4 seconds, rotate 40 deg and wait for 2 seconds, and then finally rotate rotate 20 deg.

void Start()
{
StartCoroutine(waiter());
}

IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);

//Wait for 4 seconds
yield return new WaitForSeconds(4);

//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);

//Wait for 2 seconds
yield return new WaitForSeconds(2);

//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}

2.With a coroutine and WaitForSecondsRealtime.

The only difference between WaitForSeconds and WaitForSecondsRealtime is that WaitForSecondsRealtime is using unscaled time to wait which means that when pausing a game with Time.timeScale, the WaitForSecondsRealtime function would not be affected but WaitForSeconds would.

void Start()
{
StartCoroutine(waiter());
}

IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);

//Wait for 4 seconds
yield return new WaitForSecondsRealtime(4);

//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);

//Wait for 2 seconds
yield return new WaitForSecondsRealtime(2);

//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}

Wait and still be able to see how long you have waited:

3.With a coroutine and incrementing a variable every frame with Time.deltaTime.

A good example of this is when you need the timer to display on the screen how much time it has waited. Basically like a timer.

It's also good when you want to interrupt the wait/sleep with a boolean variable when it is true. This is where yield break; can be used.

bool quit = false;

void Start()
{
StartCoroutine(waiter());
}

IEnumerator waiter()
{
float counter = 0;
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);

//Wait for 4 seconds
float waitTime = 4;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
//Wait for a frame so that Unity doesn't freeze
//Check if we want to quit this function
if (quit)
{
//Quit function
yield break;
}
yield return null;
}

//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);

//Wait for 2 seconds
waitTime = 2;
//Reset counter
counter = 0;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
//Check if we want to quit this function
if (quit)
{
//Quit function
yield break;
}
//Wait for a frame so that Unity doesn't freeze
yield return null;
}

//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}

You can still simplify this by moving the while loop into another coroutine function and yielding it and also still be able to see it counting and even interrupt the counter.

bool quit = false;

void Start()
{
StartCoroutine(waiter());
}

IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);

//Wait for 4 seconds
float waitTime = 4;
yield return wait(waitTime);

//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);

//Wait for 2 seconds
waitTime = 2;
yield return wait(waitTime);

//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}

IEnumerator wait(float waitTime)
{
float counter = 0;

while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
if (quit)
{
//Quit function
yield break;
}
//Wait for a frame so that Unity doesn't freeze
yield return null;
}
}

Wait/Sleep until variable changes or equals to another value:

4.With a coroutine and the WaitUntil function:

Wait until a condition becomes true. An example is a function that waits for player's score to be 100 then loads the next level.

float playerScore = 0;
int nextScene = 0;

void Start()
{
StartCoroutine(sceneLoader());
}

IEnumerator sceneLoader()
{
Debug.Log("Waiting for Player score to be >=100 ");
yield return new WaitUntil(() => playerScore >= 10);
Debug.Log("Player score is >=100. Loading next Level");

//Increment and Load next scene
nextScene++;
SceneManager.LoadScene(nextScene);
}

5.With a coroutine and the WaitWhile function.

Wait while a condition is true. An example is when you want to exit app when the escape key is pressed.

void Start()
{
StartCoroutine(inputWaiter());
}

IEnumerator inputWaiter()
{
Debug.Log("Waiting for the Exit button to be pressed");
yield return new WaitWhile(() => !Input.GetKeyDown(KeyCode.Escape));
Debug.Log("Exit button has been pressed. Leaving Application");

//Exit program
Quit();
}

void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}

6.With the Invoke function:

You can call tell Unity to call function in the future. When you call the Invoke function, you can pass in the time to wait before calling that function to its second parameter. The example below will call the feedDog() function after 5 seconds the Invoke is called.

void Start()
{
Invoke("feedDog", 5);
Debug.Log("Will feed dog after 5 seconds");
}

void feedDog()
{
Debug.Log("Now feeding Dog");
}

7.With the Update() function and Time.deltaTime.

It's just like #3 except that it does not use coroutine. It uses the Update function.

The problem with this is that it requires so many variables so that it won't run every time but just once when the timer is over after the wait.

float timer = 0;
bool timerReached = false;

void Update()
{
if (!timerReached)
timer += Time.deltaTime;

if (!timerReached && timer > 5)
{
Debug.Log("Done waiting");
feedDog();

//Set to false so that We don't run this again
timerReached = true;
}
}

void feedDog()
{
Debug.Log("Now feeding Dog");
}

There are still other ways to wait in Unity but you should definitely know the ones mentioned above as that makes it easier to make games in Unity. When to use each one depends on the circumstances.

For your particular issue, this is the solution:

IEnumerator showTextFuntion()
{
TextUI.text = "Welcome to Number Wizard!";
yield return new WaitForSeconds(3f);
TextUI.text = ("The highest number you can pick is " + max);
yield return new WaitForSeconds(3f);
TextUI.text = ("The lowest number you can pick is " + min);
}

And to call/start the coroutine function from your start or Update function, you call it with

StartCoroutine (showTextFuntion());

any way to make my script wait for some seconds?

Just put the code on a coroutine, and add the timeout

public void RecyclePlatform(GameObject Platform)
{
StartCoroutine(RecyclePlatformCoroutine(Platform));
}

private IEnumerator RecyclePlatformCoroutine(GameObject Platform)
{
yield return new WaitForSeconds(5);

Platform.transform.position = new Vector3(0, 0, _zedOffset);
_zedOffset += 4;
}

Unity3D: Trying to make a custom Sleep/Wait function in C#

You could do something like this:

void Start()
{
print( "Starting " + Time.time );
StartCoroutine( WaitPrintAndSetValue( 2.0F, theNewValue => example.Variable = theNewValue ) );
print( "Before WaitAndPrint Finishes " + Time.time );
}

/// <summary>Wait for the specified delay, then set some integer value to 42</summary>
IEnumerator WaitPrintAndSetValue( float waitTime, Action<int> setTheNewValue )
{
yield return new WaitForSeconds( waitTime );
print( "WaitAndPrint " + Time.time );
int newValueToSet = 42;
setTheNewValue( newValueToSet );
}

If after your delay you need to both read and update a value, you could e.g. pass Func<int> readTheOldValue, Action<int> setTheNewValue and invoke with the following lambdas () => example.Variable, theNewValue => example.Variable = theNewValue

Here's more generic example:

void Delay( float waitTime, Action act )
{
StartCoroutine( DelayImpl( waitTime, act ) );
}

IEnumerator DelayImpl( float waitTime, Action act )
{
yield return new WaitForSeconds( waitTime );
act();
}

void Example()
{
Delay( 2, () => {
print( "After the 2 seconds delay" );
// Update or get anything here, however you want.
} );
}

Unity | how to make something happen after 10 seconds without delaying game

There are lots of ways! Here are a few examples:

  1. Use a Unity Coroutine (https://docs.unity3d.com/Manual/Coroutines.html)
    void Start()
{
StartCoroutine(DoSomethingAfterTenSeconds());
}

IEnumerator DoSomethingAfterTenSeconds()
{
yield return new WaitForSeconds(10);

// now do something
}

  1. Use FixedUpdate or Update to wait 10 seconds:
    private float _delay = 10;

public void FixedUpdate()
{
if (_delay > 0)
{
_delay -= Time.fixedDeltaTime;

if (_delay <= 0)
{
// do something, it has been 10 seconds
}
}
}

  1. Use async/await instead of coroutines (https://forum.unity.com/threads/c-async-await-can-totally-replace-coroutine.1026571/)

How to wait in Unity c# function?

void Start() { }

private void OnCollisionEnter(Collision collision) {
StartCoroutine(Text());
}

IEnumerator Text()
{
yield return new WaitForSeconds(3);
rd = GetComponent<Renderer>();
rd.enabled = false;
}

How do i create a time delay before the button appears unity

For time delay you could use coroutines. Check it out here There is options like waitforseconds so you can delay your button apperance. here is sample code

private IEnumerator ShowBtn()
{
yield return new WaitWhile(() => videoplayer.isPlaying);
// show visibility of your button
}

And when you play video call this function like this

StartCoroutine(ShowBtn());


Related Topics



Leave a reply



Submit