Best way to wait for 10 minutes while keeping everything running?

Hi all,

What’s the best way to wait for 10 minutes and call a function afterwards?

  • I tried async functions but they still work even though I stopped playing the game
  • Making a float variable and increasing its value every frame isn’t efficient
  • I don’t know if coroutines are good for long wait times. I have to make it something like WaitForSeconds(600.0f)

Coroutines would be a good option

1 Like

Isn’t efficient as compared to what? Anything that’s capable of executing on the exact frame that your timer is up is going to involve performing a check every frame.

You can avoid the per-frame addition and the variable update if you precalculate the desired stop time; e.g.

float targetTime;

void Start()
{
    targetTime = Time.realtimeSinceStartup + 600;
}

void Update()
{
    if (Time.realtimeSinceStartup >= targetTime)
    {
        // Do your thing
    }
}

(You might want to use Time.time rather than Time.realtimeSinceStartup; depends what you’re measuring.)

4 Likes

I didn’t know the realtimeSinceStartup, thank you.

Increasing variable isn’t efficient in my case. If I have more than one things to check, I need to do all of them in one function. Also, when the scene changes this approach doesn’t work.

Since there’s no another way (like async functions), it looks like a singleton class is a must for me.

As @Antistone already mentioned, any solution that’s capable of executing something on the exact frame your timer runs out, will do a check per frame. If you have a lot of those timers that’s still true.

However, even if you had thousands such checks, that’s likely not gonna affect your performance at all. And i doubt you do have thousands such checks. And if these ever became a problem you could implement a data structure for optimization, which sorts the checks based on the time difference, and only checks the next timer until that one is true. But i doubt anything like this would be necessary.

As a rule of thumb: do not worry about performance until you actually run into a problem. People tend to underestimate what modern CPUs are capable of.

There is plenty ways of keeping information between scenes. Like writing it to the disk and reading it. PlayerPrefs can be used too. Or, if you literally need to keep a complex object like a timer manager… DontDestroyOnLoad is probably your friend.

2 Likes

But that’s like, the bottom-line efficiency? You can’t hardly be any more efficient than that, under the assumption that you are guaranteed to increment it every frame by a knowable amount (thus you’re covered by design).

1 Like

No no no no. You check for all those things (as other have pointed out) whether you trigger the action or not.
And the easiest way to bridge states between the scenes are static classes. You are probably the only person in the world that didn’t already abuse the fact.