- Home /

# Spawn at random?

If I set boundaries, how can I have enemies spawn at random points wit$$anonymous$$n the boundaries (like spawning at a random point wit$$anonymous$$n t$$anonymous$$s room)? Thanks.

**Answer** by skovacs1
·
Nov 18, 2010 at 03:20 PM

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 w$$anonymous$$ch 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
Instantiate(prefab, Random.insideUnitSphere * radius,
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 somet$$anonymous$$ng 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.

Anyt$$anonymous$$ng else becomes much harder, especially if you cannot guarantee the area is convex.

Subdivisions don't have to be uniform, you could just weight their probability based on their area (if 2D) or volume (if 3D).

### Your answer

### Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

### Follow this Question

### Related Questions

Object Spawning Randomly 0 Answers

Why do objects keep spawning on top of one another? 0 Answers

Random select from array and spawn 1 Answer

Creating a light in game C# 1 Answer