Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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); 
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.