- Home /
Question by
Abhaya.Agrawal · Oct 20, 2014 at 09:21 AM ·
while loop
On applying this code Unity is hanging. What is wrong with the code?
public var speed : float;
//var check : float;
function Start () {
}
function Update()
{
while(transform.position.x != 15f)
{
transform.position.x += speed * Time.deltaTime;
yield WaitForSeconds(0);
}
transform.position.x -= speed * Time.deltaTime;
}
Comment
Answer by Kiwasi · Oct 20, 2014 at 09:30 AM
Once the code is formatted properly it becomes obvious
You are trying to make Update a coroutine
You are comparing floats directly
Nice catch with the Update function coroutine thing. I clearly missed that. >.<
Answer by HarshadK · Oct 20, 2014 at 07:01 AM
Because the code is not properly formatted. ;-)
The actual reason is that you are comparing float values using == operator which is very very very less likely scenario. Hence your loop is going into infinity.
Use Mathf.Approximately to compare like:
while(!Mathf.Approximately(transform.position.x, 15f))