Wait for Real Seconds class using static function in Unity

Posted on

in

,

Paste this code into a new script called ‘CoroutineUtil’.

using UnityEngine;
using System.Collections;

public static class CoroutineUtil
{
    public static IEnumerator WaitForRealSeconds(float time)
    {
        float start = Time.realtimeSinceStartup;
        while (Time.realtimeSinceStartup < start + time)
        {
            yield return null;
        }
    }
}

What this class does is expand on the delaying code method by making it work even when the game is paused. The function is made static so that any other script can access it without having to instantiate it first (eg. making a game object and then adding the script to it). You can access the function directly from the class like so:

IEnumerator blockBtns(bool b00l){
        yield return StartCoroutine(CoroutineUtil.WaitForRealSeconds(fadeTime));
        // do stuf after time passed
    }

You can also make static variables and there would only be the one variable in the whole game.

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

April 2025
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
282930