英文:
How do i put a delay in a while loop in Unity?
问题
I just want a simple way to delay a while loop. I'm using C#.
Here's my code:
while (value < 101)
{
Debug.Log(value);
value = value + 10;
// 在这里延迟(我不知道如何做)
}
我只想要一个简单的方法来延迟一个 while 循环。我正在使用 C#。
这是我的代码:
while (value < 101)
{
Debug.Log(value);
value = value + 10;
// 在这里延迟(我不知道如何做)
}
英文:
I just want a simple way to delay a while loop. I'm using C#.
Here's my code:
while (value<101)
{
Debug.Log(value);
value = value + 10;
//delay here (that i don't know how to do)
}
I used a bit of google translate so the text might be bad.
答案1
得分: 4
Unity允许您使用协程延迟代码执行。这避免了暂停整个线程,不像Thread.Sleep()。要在while循环中添加延迟,您可以这样做:
private IEnumerator DelayedWhileLoop()
{
int value = 0;
while (value < 101)
{
Debug.Log(value);
value += 10;
yield return new WaitForSeconds(1); // 延迟1秒
}
}
void Start()
{
StartCoroutine(DelayedWhileLoop());
}
英文:
Unity allows you to delay code execution using coroutines. This avoids pausing the entire thread, unlike Thread.Sleep(). To add a delay to a while loop you could do something like this:
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());
}
答案2
得分: 0
你可以使用Unity的Coroutine函数来实现这个,带有延迟。请运行以下代码:
public class LoopWithDelayExample : MonoBehaviour
{
private bool isRunning = false;
// 启动Coroutine
public void StartCoroutineTest()
{
if (!isRunning)
{
StartCoroutine(DelayCoroutineWithLoop());
}
}
// 带延迟的Coroutine
private IEnumerator DelayCoroutineWithLoop()
{
isRunning = true;
float loopingTime = 5f; // 循环的持续时间(秒)。
float delay = 2f; // 延迟的持续时间(秒)。
float startTime = Time.time;
float endTime = startTime + loopingTime;
// 在给定的持续时间内循环
while (Time.time < endTime)
{
Debug.Log("Loop is running...");
// 等待下一帧。
yield return null;
}
// 延迟指定的持续时间。
yield return new WaitForSeconds(delay);
// 重置变量
isRunning = false;
}
}
请注意,这是Unity中用于在一段时间内执行循环并添加延迟的示例代码。
英文:
you can do this using Unity's Coroutine function with delay.
Please run the beloved code.
public class LoopWithDelayExample : MonoBehaviour
{
private bool 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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论