延迟执行';如果';统一声明C#
我希望在第一段代码完成后直接执行一段特定的代码,而不是像当前运行的代码那样同时执行延迟执行';如果';统一声明C#,c#,unity3d,C#,Unity3d,我希望在第一段代码完成后直接执行一段特定的代码,而不是像当前运行的代码那样同时执行 private void Update() { //This is the code to be executed first if ((textActive == true) && (stopText == false)) { Debug.Log("TextActive"); KeyText("On"); objectToE
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秒,以便有时间播放动画
提前感谢您的帮助。使用协同程序的好时机:
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);
}
}
根据您提供的代码,我认为他们正在做您希望它做的事情:按顺序执行。但是,由于代码非常简单,因此看起来它们可能同时运行,这使得您根本看不到objectToEnable4。暂停执行的方法是使用Unity的协同程序 以下代码是Unity Scriptping API中的协同程序示例:
using UnityEngine;
using System.Collections;
public class WaitForSecondsExample : MonoBehaviour
{
void Start()
{
StartCoroutine(Example());
}
IEnumerator Example()
{
print(Time.time);
yield return new WaitForSecondsRealtime(5);
print(Time.time);
}
}
第一个答案完美地将corotine应用于您的代码。希望您觉得它有用。在我看来,使用Invoke还有一种更好(至少更简单)的方法
private void Update()
{
if (textActive && !stopText)
{
KeyText("On");
objectToEnable4.SetActive(true);
stopText = true;
Invoke("MyDelay", 2);
}
}
private void MyDelay()
{
if (stopText)
{
objectToEnable4.SetActive(false);
}
}
我不知道为什么你甚至需要使用boolstopText,也许是为了一些你没有给我们看的东西?如果不是,你也可以删除它 非常感谢您的贡献:)