提问人:Electrico28 提问时间:7/20/2023 最后编辑:Daniel A. WhiteElectrico28 更新时间:7/20/2023 访问量:163
如何在 Unity 中将延迟置于 while 循环中?[复制]
How do i put a delay in a while loop in Unity? [duplicate]
问:
我只想要一种延迟 while 循环的简单方法。我正在使用 C#。 这是我的代码:
while (value<101)
{
Debug.Log(value);
value = value + 10;
//delay here (that i don't know how to do)
}
我用了一点谷歌翻译,所以文字可能很糟糕。
答:
4赞
SetupWizard
7/20/2023
#1
Unity 允许您使用协程延迟代码执行。这与 Thread.Sleep() 不同,这避免了暂停整个线程。要向 while 循环添加延迟,您可以执行如下操作:
private IEnumerator DelayedWhileLoop()
{
int value = 0;
while (value < 101)
{
Debug.Log(value);
value += 10;
yield return new WaitForSeconds(1); // Delay for 1 second
}
}
void Start()
{
StartCoroutine(DelayedWhileLoop());
}
0赞
Sudhir Kotila
7/20/2023
#2
您可以使用 Unity 的 Coroutine 函数(带延迟)来执行此操作。 请运行心爱的代码。 公共类 LoopWithDelayExample : MonoBehaviour { 私有布尔值 isRunning = false;
// Start Coroutine
public void StartCoroutineTest()
{
if (!isRunning)
{
StartCoroutine(DelayCoroutineWithLoop());
}
}
// Delayed Coroutine
private IEnumerator DelayCoroutineWithLoop()
{
isRunning = true;
float loopingTime = 5f; // The duration of the loop in seconds.
float delay = 2f; // The delay duration in seconds.
float startTime = Time.time;
float endTime = startTime + loopingTime;
// Loop for given duration
while (Time.time < endTime)
{
Debug.Log("Loop is running...");
// Wait for the next frame.
yield return null;
}
// Delay for the specified duration.
yield return new WaitForSeconds(delay);
//Reset Vars
isRunning = false;
}
}
上一个:而循环停止处理大数 C#
评论
Thread.Sleep()
Thread.Sleep
Update
value
Thread.Sleep