Random Spawner using radius and numbers

I am wanting to make a javascript script people can download and import into unity and use to easily create RPG mob spawners. In there, I have variables which the user can set the amount of mobs to spawn and the radius around the spawner (Which is just an empty game object). I want to know how or where I can learn how to make them randomly spawn within that radius.

Can anyone please help me?

Do you insist on it spawning inside a sphere?

Because it's definitely possible, it's just a bit harder to explain how to :)

3 Answers

3

http://unity3d.com/support/documentation/ScriptReference/Random-insideUnitCircle.html and http://unity3d.com/support/documentation/ScriptReference/Random-insideUnitSphere.html and http://unity3d.com/support/documentation/ScriptReference/Object.Instantiate.html

I'd try:

var ran = Random.insideUnitSphere * mobSpawnRadius;
ran.y = 0.0;
var mobSpawnLocation : Vector3 = transform.position + ran;

The above post nails it. A sphere is definitely the easiest, anything else would require more calculations and more information.

If you care about the math, it’s just X = spawnpoint.x + random(-radius,radius) and the same for Z.

If you’re using Unity Terrain you can use the SampleHeight method to get the ground level at the point you’ve selected. Depending on how many mobs you’re spawning and how small the radius is, the likelihood of spawning units on top of each other is pretty low, but you may not even care about that.

I think I have one good solution after doing a lot more poking around unity answers, and I seem to have managed getting the radius spawner with this

public var mobName : String;                                 // Sets the name of the mob that spawns in this area
public var mobPrefab : GameObject;                          // Sets the prefab of the mob that you are spawning in this area
public var mobSpawnNumber : int;                                // Sets the amount of mobs to spawn in this area
public var mobSpawnRadius : float;                          // Sets the radius of the area of which to spawn the mobs around the spawner

function Start() {
    var mobSpawnLocation : Vector3 = new Vector3(Random.Range(this.transform.position.x, mobSpawnRadius), this.transform.position.y, Random.Range(this.transform.position.z, mobSpawnRadius));
    Instantiate (mobPrefab, mobSpawnLocation, transform.rotation);
}

And it has seemed to work well. Should I use a for loop on the mobSpawnNumber when choosing how many to spawn?

Actually, nevermind, that third link says it right there. Thanks =o)

Edited my answer to reflect more like what you may need.