Ankur Lathwal
Ankur Lathwal

Reputation: 725

How to insert a time gap of 2 seconds between execution of two statements in C#?

I am building a simple 2D game using Unity.In my C# script,i want to insert a gap of 2 seconds between two consecutive statements.

void OnGUI()
{


    GUI.Button (new Rect(400,40,45,45),"text1");
    // time gap statement
    GUI.Button (new Rect(800,40,45,45),"text1");

    } 

It means that i want a button to be created and displayed and after that wait for 2 seconds before next button is created and displayed on screen. Any easy way to do this??

Upvotes: 0

Views: 931

Answers (2)

Formic
Formic

Reputation: 650

You could use a Coroutine to do a delay, but that's not really appropriate since you are displaying this in OnGUI.

Try something like this:

public float secondButtonDelay = 2.0f; // time in seconds for a delay

bool isShowingButtons = false;
float showTime;

void Start()
{
     ShowButtons(); // remove this if you don't want the buttons to show on start
}

void ShowButtons()
{
    isShowingButtons = true;
    showTime = Time.time;
}

void OnGUI()
{
     if (isShowingButtons)
     {
         GUI.Button (new Rect(400,40,45,45),"text1");

         if (showTime + secondButtonDelay >= Time.time)
         {
             GUI.Button (new Rect(800,40,45,45),"text1");
         }
     }
}

Upvotes: 4

luqui
luqui

Reputation: 60463

OnGUI is executed approximately every frame to draw the user interface, so you can't use delays like this. Instead, conditionally draw the second element based on some condition that becomes true, e.g.

void OnGUI()
{
    GUI.Button (new Rect(400,40,45,45),"text1");
    if (Time.time > 2) {
        GUI.Button (new Rect(800,40,45,45),"text1");
    }
} 

Upvotes: 3

Related Questions