You can use yield return new WaitForSeconds() in a coroutine if you want to wait for a specific amount of time in unity.
Coroutine pause execution of code when it reaches at yield return and wait for the time we passed in WaitForSeconds(Seconds) method and then execute code that is after this statement. WaitForSeconds(Seconds) takes only single parameter that is number of seconds we want to wait.
A coroutine example for waiting for 2 seconds is given below:
StartCoroutine() can only be called from MonoBehaviour component which is attached with a gameObject.
We can also use WaitForSecondsRealtime() instead for WaitForSeconds() statement both work in same way there is only a single difference that WaitForSecondsRealtime() wait for time in real time regardless of game status whether game is paused or not like timeScale is 0, 1 or anything else.
A coroutine example for waiting for 2 seconds in real-time and then print message is given below:
We can set Time.timeScale value to 0 so it will pause all physics and animations and after that time passed we can set Time.timeScale value back to 1.
Now we use DateTime.Now.AddSeconds(1) to add a second in current time and then we use while loop for checking if current time is greater then our added time.
You must note that you can use any method according to your need.
Comments
Post a Comment