- Home /
Question by
off112 · Jun 21, 2018 at 06:58 PM ·
spawnwhile loop
while loop freeze when trying to spawn object
Hi,
I want to prevent my enemy to spawn on my player. I have tried to do it with a while loop, but it always freeze the game. Could someone help me
Here is my code:
public GameObject Enemy;
public GameObject Player;
public void Start () {
//Create a new enemy.
Instantiate(Enemy, SpawnPosition(), Quaternion.identity);
}
//Create enemy position.
Vector2 SpawnPosition(){
float x, y;
x = Random.Range(-2.7f, 2.7f);
y = Random.Range(3.8f, -4.0f);
//Create new place to spawn outside player.
while(Vector2.Distance(Player.transform.position,new Vector2(x, y)) < 7 )
{
x = Random.Range(-2.7f, 2.7f);
y = Random.Range(3.8f, -4.0f);
}
return new Vector2(x, y);
}
Comment
Answer by SlowCircuit · Jun 21, 2018 at 07:14 PM
If it freezes then the loop is running itself over and over again infinitely. I assume that means that your distance is never above 7. To fix this, just increase the values in your random ranges until the distance can reach above 7. I would recommend also have in an int that counts how many times the loop runs and do a Debug.Log of the int after the loop. That way you can see if your values are still too low causing the loop to take a really long time to work.