简体   繁体   English

如何在C#中执行两个语句之间插入2秒的时间间隔?

[英]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. 我正在使用Unity构建一个简单的2D游戏。在我的C#脚本中,我想在两个连续的语句之间插入2秒的间隔。

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. 这意味着我要创建和显示一个按钮,然后等待2秒钟,然后创建下一个按钮并将其显示在屏幕上。 Any easy way to do this?? 任何简单的方法来做到这一点?

You could use a Coroutine to do a delay, but that's not really appropriate since you are displaying this in OnGUI. 您可以使用协程进行延迟,但这并不是真正合适的方法,因为您是在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");
         }
     }
}

OnGUI is executed approximately every frame to draw the user interface, so you can't use delays like this. OnGUI几乎每帧都执行一次以绘制用户界面,因此您不能使用这种延迟。 Instead, conditionally draw the second element based on some condition that becomes true, eg 取而代之的是,根据某些条件变为真,有条件地绘制第二个元素,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM