【问题标题】:How to insert a time gap of 2 seconds between execution of two statements in C#?如何在 C# 中执行两条语句之间插入 2 秒的时间间隔?
【发布时间】:2014-07-01 16:37:59
【问题描述】:

我正在使用 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");

    } 

这意味着我希望创建和显示一个按钮,然后等待 2 秒钟,然后再创建下一个按钮并在屏幕上显示。 有什么简单的方法吗??

【问题讨论】:

  • @Derek 我假设您忘记在您的Thread.Sleep(2000) 之前添加“甚至不要尝试使用”。否则这是非常糟糕的建议。

标签: c# unity3d time-wait


【解决方案1】:

您可以使用Coroutine 进行延迟,但这并不合适,因为您是在 OnGUI 中显示的。

试试这样的:

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

【讨论】:

    【解决方案2】:

    OnGUI 大约每帧执行一次以绘制用户界面,因此您不能使用这样的延迟。相反,根据某个条件为真有条件地绘制第二个元素,例如

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

    【讨论】:

    • 好兄弟!简短而简单。 :)
    猜你喜欢
    • 2011-03-12
    • 1970-01-01
    • 2019-05-17
    • 2020-02-26
    • 2017-09-05
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多