Here is my code.. I have explained the issue after..
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) visibly changes the color of one 3D arrow in a sequence of 3D arrows (arrow1, then arrow2, etc) to show direction. something like this.. i just want to add a time delay in between each color change, but none of the attempts i've made seem to create a time delay when i enter play mode and press Backspace key.
the colors flash extremely fast. There is no waiting between color changes whatsoever.. even when running the coroutine, while loop and for loop together :(
What is going on and how do i fix it??
CodePudding user response:
The issue with the for loop is that you aren't waiting for the actual time between fixed updates and rather using the time between the last fixed update and adding it as fast as your CPU will until timer is larger than 2. The coroutine will wait 2 seconds before logging it's output. You need to put your arrow change code in the coroutine, because the Coroutine essentially works in "parallel" to your FixedUpdate.
So either do:
void FixedUpdate()
{
timer = Time.deltaTime;
if(timer >= 2.0f) {
//arrow thingy
timer = 0;
}
}
or in the Coroutine:
IEnumerator TimeDelay()
{
yield return new WaitForSeconds(2f);
//arrow thingy
}
In this state the FixedUpdate version will loop indefinitely and call arrow thingy roughly each two seconds, and the Coroutine will do so once.
A quick side note you should probably use Update and DeltaTime for this and not FixedUpdate with FixedDeltaTime.