首页 > 解决方案 > 在 Unity C# 中延迟执行“If”语句

问题描述

我希望在第一个代码完成后直接执行一段特定的代码,而不是像它们当前正在运行的同时执行。

private void Update()
{
    //This is the code to be executed first
    if ((textActive == true) && (stopText == false))
    {
        Debug.Log("TextActive");
        KeyText("On");
        objectToEnable4.SetActive(true);
        stopText = true;
    }    

    //after which this code will execute to disable Object4
    if (stopText == true)
    {

        objectToEnable4.SetActive(false);
    }
}

两段代码都完美运行我只需要为第二个代码部分实现延迟我希望将代码延迟 2 秒以留出时间播放动画

我在这里先向您的帮助表示感谢。

标签: c#unity3d

解决方案


使用协程的好时机:

private void Update()
{
    //This is the code to be executed first
    if ((textActive == true) && (stopText == false))
    {
        Debug.Log("TextActive");
        KeyText("On");
        objectToEnable4.SetActive(true);
        stopText = true;
        StartCoroutine(myDelay());
    }
}

IEnumerator myDelay()
{
    // waits for two seconds before continuing
    yield return new WaitForSeconds(2f);

    if (stopText == true)
    {
        objectToEnable4.SetActive(false);
    }
}

推荐阅读