我正在尝试在 Unity 中实现时间延迟。我已经使用 while 循环、for 循环和协同程序完成了它,但其中 none 似乎有效

I'm trying to implement a time delay in Unity. I have done it using while loop, for loop and coroutines, but none of them seem to work

这是我的代码..我已经解释了这个问题..

public bool isPipeActive;

[SerializeField] private float timer;

void Start()
{
    isPipeActive = false;
    timer = 0f;
}

void FixedUpdate()
{
    if (Input.GetKeyDown(KeyCode.Backspace))
    {
        isPipeActive = !isPipeActive; //bool flag invert
        
    }

    if (isPipeActive == true) //start pipe animations
    {
        for (int j = 0; j < ParentOf_arrow.transform.childCount; j++)
        {
            Initiate_arrow_FLOW_INDICATOR(j);

            StartCoroutine(Time_Delay());

            //while (timer < 1.0f)
            for (timer = 0f; timer < 2.0f; timer += Time.fixedDeltaTime)
            {
                //just a blank function to see if it creates a delay..
                timer += Time.fixedDeltaTime;
            }
            //timer = 0f;

        }
    }
    
     
}

IEnumerator Time_Delay()
    {
        yield return new WaitForSeconds(2f);
        Debug.Log("2s delay initiated");
    }

Initiate_arrow_FLOW_INDICATOR(j) 明显地改变了一系列 3D 箭头(arrow1,然后是 arrow2,等等)中一个 3D 箭头的颜色以显示方向。 something like this.. 我只是想在每次颜色变化之间添加一个时间延迟,但是当我进入播放模式并按退格键时,我所做的 none 尝试似乎会造成时间延迟。

颜色闪烁得非常快。任何颜色变化之间都没有等待.. 即使 运行 协程,while 循环和 for 循环在一起 :(

这是怎么回事,我该如何解决?

for 循环的问题在于,您不是在等待固定更新之间的实际时间,而是使用上次固定更新之间的时间,然后像 CPU 一样快地添加它,直到计时器大于 2。 协程将在记录其输出之前等待 2 秒。 您需要将箭头更改代码放在协程中,因为协程基本上与您的固定更新“并行”工作。

所以要么:

void FixedUpdate()
{
   timer += Time.deltaTime;
   if(timer >= 2.0f) {
     //arrow thingy
     timer = 0;
    }
}

或者在协程中:

IEnumerator TimeDelay()
{
    yield return new WaitForSeconds(2f);
    //arrow thingy
}

在此状态下,FixedUpdate 版本将无限循环并大约每两秒调用一次箭头,协程将执行一次。
一个快速的旁注,你应该为此使用 Update 和 DeltaTime 而不是 FixedUpdate 和 FixedDeltaTime。