Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

WaitForSeconds while time.scale=0?

Discussion in 'Editor & General Support' started by ADNCG, Oct 8, 2014.

  1. ADNCG

    ADNCG

    Joined:
    Jun 9, 2014
    Posts:
    989
    Hello dear unity users,

    I'm trying to figure out if there's a way to execute coroutines with waitforseconds functions while Time.Scale=0;

    Basically, I want to run some lines that are time dependant while the game is paused, and I'd rather not have to pause everything manually.

    Or, is there by any chance a way to have 2 different time variables that I could refer to. In which case I'd have some part of a script refer to the new time variable, while everything else refers to the built in time.scale(if that makes any sense at all)?

    Thanks

    Edit : Just now realized that I posted in the wrong section. Apologies for that.
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    Unity offers Time.realTimeSinceStartup and Time.unscaledDeltaTime for keeping track of the real time that has passed.

    Here is one way you could do it:
    Code (csharp):
    1. IEnumerator Foo () {
    2.     yield StartCoroutine (WaitForRealSeconds (5));
    3. }
    4.  
    5. IEnumerator WaitForRealSeconds (float seconds) {
    6.     float startTime = Time.realTimeSinceStartup;
    7.     while (Time.realTimeSinceStartup-startTime < seconds) {
    8.         yield return null;
    9.     }
    10. }
     
  3. ADNCG

    ADNCG

    Joined:
    Jun 9, 2014
    Posts:
    989
    That is exactly what I was looking for. Thank you for your time, have a great day.
     
  4. Tommy4421

    Tommy4421

    Joined:
    Nov 12, 2016
    Posts:
    5
    There is an new method now: yield return new WaitForSecondsRealtime(time);
     
  5. bwulff

    bwulff

    Joined:
    Jun 20, 2020
    Posts:
    12
    Thank you!
     
    Michael_Berna and Looujk like this.
  6. xCyborg

    xCyborg

    Joined:
    Oct 4, 2010
    Posts:
    625
    That one is indeed underrated.
     
    manbearpigman likes this.