# Using for as while.

I need to rerandom a number each time if condition equals false.
With while it would look:

``````float Distance;
float minDistance;
Vector3 Position;

while(Distance < minDistance)
{
Position = new Vector3(Random.Range(50,-50),Random.Range(50,-50),0);
}
``````

But using while in Update will freeze unity. So how can i do the same using “for” loop ?Thanks!

``````float Distance;
float minDistance;
Vector3 Position;

for(Distance = Vector3.Distance(transform.position,bla.position);Distance < minDistance;)
{
Position = new Vector3(Random.Range(50,-50),Random.Range(50,-50),0);
}
``````

Unless you absolutely want to use for or while, you could just do:

``````    bool condition = false;

void Update()
{
if(!condition)
{
//Random Range Code Here
condition = true;
}

}
``````

The while loop works as long as you recalculate the Distance from within the loop, like so

``````while(Distance < minDistance)
{
Position = new Vector3(Random.Range(50,-50),Random.Range(50,-50),0);
Distance = Vector3.Distance(transform.position,Position);
}
``````

Seeing what you are trying to achieve, let’s try another way.

You want to create an object that would be outside the radius of a circle with the player position at the center.

The other way could be to first get a random direction and then get a random distance greater than distance.

``````void CreateAtDistance(){
Vector3 direction = new Vector3(Random.Range(-1.0f,1.0f),Random.Range(-1.0f,1.0f),0);
direction.Normalize();
float distance = Random.Range(minDistance, 50);
direction *= distance;
NewPosition = Position + direction;
}
``````

You will have to try this as I cannot…but the idea is as I said, first define a direction. Then you normalize the vector so that it has length 1. Then you multiply by a value between minDistance and max distance (I chose 50).
Then you multiply the vector to extend it. Then you do an addition of the position and the direction.