# Spawn at random?

If I set boundaries, how can I have enemies spawn at random points within the boundaries (like spawning at a random point within this room)? Thanks.

You would need to get your room dimensions somehow (I assume that's what you mean by "if I set boundaries"), then you can use a random value for your instantiate position.

Instantiate in a circle:

``````//Assumes you know the radius of the area and the height at which to instantiate
var pos : Vector2 = Random.insideUnitCircle * radius;
Instantiate(prefab, Vector3(pos.x,height,pos.y),
Quaternion.LookRotation(center));

``````

or inside a sphere:

``````//Assumes you know the radius of the area
Quaternion.LookRotation(center));

``````

or in a box:

``````//Assumes Vector3's for the minimum and maximum positions
Instantiate(prefab, Vector3(Random.Range(minimum.x,maximum.x),
Random.Range(minimum.y,maximum.y),
Random.Range(minimum.z,maximum.z)),
Quaternion.LookRotation(center));

``````

For arbitrarily shaped areas, you would have to write something more complicated. The brute force solution is to keep generating points until you get one inside the volume.

Another more storage-intensive approach (at least when doing the calculation of the subdivisions) is to subdivide the area into equal and uniform divisions and then pick one at random to position yourself in and, since the area is uniform, from there, it would be as the simple code above.

Anything else becomes much harder, especially if you cannot guarantee the area is convex.