I’m making a top-down shooter and I want to spawn objects around the player in random positions unless the random position is within a certain distance of the player.
This will spawn the object in a random spot on the screen:
You can repeat the pos generation whenever the position is below some distance:
do {
pos = Vector3(Random.Range(-10.0,10.0), 0, Random.Range(-10.0,10.0));
} while (Vector3.Distance(pos, transform.position) < minDistance);
Instantiate(myObject,pos,transform.rotation);
NOTE: Using integers (-10, 10) in Random.Range will return an integer value between -10 and 9. If you pass float numbers to it like in the code above, the value returned will be a float between -10 and 10. But you have an even better alternative - use Random.insideUnitCircle instead:
do {
var rnd: Vector2 = 10 * Random.insideUnitCircle;
pos = Vector3(rnd.x, 0, rnd.y);
} while (Vector3.Distance(pos, transform.position) < minDistance);
Instantiate(myObject,pos,transform.rotation);