Search code examples
c#unity-game-enginetime-wait

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??


Solution

  • 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");
        }
    }