Random spawn

Hi guys , can you help me with random spawn enemyes ?

One way to accomplish this is to create some prefabs that are ready.

Then create a new script with references to the prefabs and a Spawn method. Then you just call Spawn to create a new object with a random orientation located somewhere between the origin and maxPos.

public Vector3 maxPos;
public Object myPrefab;

GameObject Spawn() {
    return Object.Instantiate(myPrefab, 
                              new Vector3(Random.value * maxPos.x,                                                      
                                          Random.value * maxPos.y, 
                                          Random.value * maxPos.z), 
                              Random.rotation);
}

Azound provided a good way to put objects at a random position, but if you were looking for a way to make a random type of enemy at a given point, here is the script:

#pragma strict
var ObjectsToSpawn : GameObject[];
var PlaceToSpawn : Vector3;
private var Selected : int;

function Spawn(){
Selected = Random.Range(0,ObjectsToSpawn.Length);
Instantiate(ObjectsToSpawn[Selected],PlaceToSpawn,Quaternion.identity);
}

Simply create the objects you want to spawn and place them in the array, then specify the place they will spawn. Then just call Spawn() from a script. If you want an object to be spawned more often, simply put it in the array multiple times.

I combined both ideas in the following script, so when Spawn() is called, a random object will be spawned at a random point in a given area with boundaries you determine.

#pragma strict
var ObjectsToSpawn : GameObject[];
var MinPosition : Vector3;
var MaxPosition : Vector3;
private var PlaceToSpawn : Vector3;
private var Selected : int;
function Spawn(){
Selected = Random.Range(0,ObjectsToSpawn.Length);
PlaceToSpawn.x = Random.Range(MinPosition.x,MaxPosition.x);
PlaceToSpawn.y = Random.Range(MinPosition.y,MaxPosition.y);
PlaceToSpawn.z = Random.Range(MinPosition.z,MaxPosition.z);
Instantiate(ObjectsToSpawn[Selected],PlaceToSpawn,Quaternion.identity);
}

Now, create prefabs and add them to the ObjectsToSpawn array as before, but instead of specifying 1 Vector3 to be the Spawnpoint, specify the minimum position and the maximum position. These can be thought of as opposite vertices of a cube, and any object in the array can be put in any point in the cube when Spawn() is called. This is great for creating enemy spawners. If you want to exclude an axis, simply set the minimum and maximum values of that axis to the same value.