- Home /
Yield return inside a loop slowdown problem
During Update (and using flags to call it whenever I do certain button presses) I call the FlipDiDoo coroutine to rotate a group of gameobjects. IEnumerator FlipDiDoo() { float anguloDeseado = 0.0f;
for (float iter = 0.0f; iter < 180; iter += 1.0f){
yield return StartCoroutine (Wait (1.0f));
foreach (GameObject hoja in hojas) {
hoja.transform.RotateAround (transform.position, ejeRot, -1);
}
//Debug.Log (iter);
}
foreach (GameObject folha in hojas) {
folha.transform.eulerAngles = new Vector3 (Mathf.Round (folha.transform.eulerAngles.x), Mathf.Round (folha.transform.eulerAngles.y), Mathf.Round (folha.transform.eulerAngles.z));
}
control.GetComponent<CameraZoomPinch>().isFlipping = false;
}
IEnumerator Wait(float duration){
for (float timer = 0; timer < duration; timer += Time.deltaTime){
yield return 0;
Debug.Log("TIMER " + timer);
}
}
I need it to do a smooth 180º rotation, which it does… until I lower the value I pass into the Wait coroutine. If it's 0.01f it should rotate one degree every 0.01 seconds, totalling 1.8 seconds for the full 180º rotation, right? Except it doesn't, it slows down horribly, totalling somewhere between 10 -15 seconds. I even tried:
Removing the foreach to see if that was where the delay came from, which didn't remove the delay.
Changing the Wait value to 0.0f, to no avail.
Taking away the yield call to the Wait subroutine, which eliminated the smoothness altogether.
Using a yield return call instead, which also caused slowdown.
Changing the for loop to a while/adding value inside the loop, with the same slowdown result.
So, I'm guessing it has something to do with calling a yield inside a loop but I just can't find exactly what I'm missing. This is usually a good place (I haven't needed to ask something here EVER, which says a lot about it's usefulness) to troubleshoot but this is really cracking my head. Any other info you need, I'll be glad to provide. Thanks in advance.
Answer by Patel-Sagar · Apr 10, 2014 at 06:08 AM
You should try mathf.lerp. it will give you smoothness, guarantee to reach 180 in your time and also device FPS independence.
I'll look into it, modify my code accordingly and get back to you via this thread with any questions if you don't $$anonymous$$d. Thanks!
Answer by sopesope · Apr 11, 2014 at 12:07 AM
I ended up doing a variation on this solution, which works just fine and does exactly what I was aiming for: http://answers.unity3d.com/questions/29110/easing-a-rotation-of-rotate-around.html
Your answer
Follow this Question
Related Questions
How to use Coroutines in C++/CLI? 1 Answer
Having trouble using coroutines, making unity hang 0 Answers
Coroutines not passing yield 1 Answer
WaitUntil doesn't work and the coroutine starts anyways 1 Answer
Mysteries of yield 1 Answer