Random spawn on screen
Hello everyone, I am trying to create a 2d game where objects are spawned in screen. I achieved it by using a random number using Random.range. Unfortunately there is an object in the middle of screen where i want the spawned object not to collide. How can i achieve this? Sry for silly question! Thanks in advance!
Answer by Polymo · Sep 12, 2015 at 10:21 AM
you could either do it in a while loop where you check with physics2d overlapsphere for example, but that could lead to an infinite loop if theres not space left. Or you can pregenerate a 2dimensional array of positions that span the whole screen, offset each of them by a small random amount and check this array for valid positions; modifications could be skipping indices into this array by a certain amount (wrapping at end) and stopping after a certain number of checks.
The second one is a pretty good idea! I'll try it out and i'll answear as soon as i achieve it.
Your answer
![](https://koobas.hobune.stream/wayback/20220612033403im_/https://answers.unity.com/themes/thub/images/avi.jpg)