# How to randomly spawn object using instantiate

I'm trying to spawn objects which move in one direction until they hit a player or the barrier. The spawner is a cube which moves between two points to spawn the object at different locations.

The code I am using is:

#pragma strict
var speed : int = 1;
var direction : int = 1;
var shot : Transform;

var lastSpawn : float;
var nextSpawn : int;

function Update () {
transform.Translate(Vector3(0, direction * speed * Time.deltaTime, 0));
if (Time.time > lastSpawn + nextSpawn){
Instantiate(shot, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), Quaternion.identity);
}

lastSpawn = Time.time;
nextSpawn = Random.Range(1, 3);
}


All the prefabs and gameObjects are assigned correctly. Should this code work or am I doing something wrong?

I am not sure to understand completely what is your problem.

Although, lastSpawn = Time.time should not be called at every frame but rather when you create a new object. I don't see a reason to have nextSpawn = Random.Range(1, 3); out of the braces but that should not be a problem.

function Update ()
{
transform.Translate(Vector3(0, direction * speed * Time.deltaTime, 0));
if (Time.time > lastSpawn + nextSpawn)
{
Instantiate(shot, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), Quaternion.identity);

lastSpawn = Time.time;
nextSpawn = Random.Range(1, 3);
}
}