如何在 Unity 中将延迟置于 while 循环中?[复制]

How do i put a delay in a while loop in Unity? [duplicate]

提问人:Electrico28 提问时间:7/20/2023 最后编辑:Daniel A. WhiteElectrico28 更新时间:7/20/2023 访问量:163

问:

我只想要一种延迟 while 循环的简单方法。我正在使用 C#。 这是我的代码:

while (value<101)
{
    Debug.Log(value);
    value = value + 10;
    //delay here (that i don't know how to do)
}

我用了一点谷歌翻译,所以文字可能很糟糕。

C# unity-game-engine while-loop 延迟 等待

评论

0赞 Daniel A. White 7/20/2023
为什么?你不应该试图阻止事情
0赞 SetupWizard 7/20/2023
@dmedine 我强烈建议不要在Unity中使用,因为它会暂停整个游戏并冻结其他脚本(除非这是您想要的)。Thread.Sleep()
0赞 derHugo 7/20/2023
@dmedine,是的,当然是完全暂停线程的通用方法。问题是你肯定不想暂停应用程序的UI主线程;)在Unity中,除非你明确地告诉它,否则默认情况下,一切都在主线程上运行,此外,大多数API仅在主线程上可用;)Thread.Sleep
0赞 derHugo 7/20/2023
你到底想达到什么目的?为此,您可能根本不需要循环 - 请记住,每帧运行一次,因此您可能还可以使用一个简单的计数器,该计数器每帧增加一点,一旦超过某个值(您想要的延迟),您就会增加Updatevalue
0赞 Enigmativity 7/21/2023
@dmedine - 如果您用于在 .NET 中暂停循环,那么您可能做错了什么。Thread.Sleep

答:

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