Hi all,
I’ve got a problem with an infinite while loop that ignores conditions and makes GameObject behave strangly.
Have a look at the code:
private IEnumerator Fall()
{
float timer = 0;
speed = 0;
while (gameObject.transform.position.y > -5)
{
timer += Time.deltaTime;
speed = timer * timer * 20;
gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, new Vector3(gameObject.transform.position.x, -10, -5), speed);
yield return 0;
}
Destroy(gameObject);
}
Now, here’s what’s happening.
-
The gameObject is shaking.
-
It goes down to some certain level (under -10) or falls infinitly.
-
The ‘while’ loop never ends, however adding
if(gameObject.transform.position.y <= -5)
break;
inside those loop fixes this issue as the object is finally being destroyed.
How can I make it work properly? Is it a common issue with ‘while’ loops in coroutines?
Hi @Legend_Bacon,
I deal with it like this:
void OnTriggerEnter2D(Collider2D other)
{
if (once && active == 0)
{
StartCoroutine(Fall());
once = false;
}
}
and it also works fine creating only one Coroutine at once. I’ve tested my code on 3 different computers with different versions of Unity and it was bugged in every case.
The problem was most certainly that other coroutine called in the same class might been unfinished. Can’t really reproduce that as it was a long time ago but as I can see the coroutines have been merged as their structure didn’t make much sense:
- First coroutine was called in an OnTriggerEnter2D method
- Second coroutine was called in the first one
- The object was supposed to destroy itself at the end but the first coroutine could be still doing it’s job
Can’t really tell if that was what fixed the issue but one I can tell - it’s no more a problem in my code. Hope it will help someone!
@DDeathlonger, your case seems different but as someone stated flipping calls fixed it so maybe it’s the right way!