Multiple spawn points using Array...

I’m trying to make a spawn script that would randomly choose one of three spawn points which are located at three game objects. This is the first set of code I tried.

var spawn : Transform[]; 
var game_cube : Rigidbody;
var cube_count = 0;

InvokeRepeating("LaunchProjectile", 2, 3);
function Update() {
    if (cube_count>= 10) {
       CancelInvoke();
    }

}

function LaunchProjectile () {
    var randomPick : int = Random.Range(0,2);

    instance = Instantiate(game_cube, spawn[randomPick].position, transform.rotation);
    instance.velocity = Vector3.zero;
    cube_count = cube_count +1;

}

It has no errors but the prefab objects I made are not spawning at all. So I tried making a basic script that could make it at least functional.

var game_cube : Rigidbody;
var spawn : Transform[];
var cube_count = 0;
var respawn1 : GameObject;
var respawn2 : GameObject;
var respawn3 : GameObject;

InvokeRepeating("LaunchProjectile", 2, 3);
function Update() {
	if (cube_count>= 10) {
		CancelInvoke();
	}

}

function LaunchProjectile () {
	var randomPick : int = Random.Range(0,2);
		if(randomPick : 0){
			spawn : respawn1;
		}
		if(randomPick : 1){
			spawn : respawn2;
		}
		if(randomPick : 2){
			spawn : respawn3;
		}
		
	instance = Instantiate(game_cube, spawn.position, spawn.rotation);
	instance.velocity = Vector3.zero;
	cube_count = cube_count +1;

}

I assume you assigned 3 transforms to 'spawn' with the Inspector, as well as game_cube?

–

1 Answer

1

You were on the right track, but you havnt started the invoke command at all, it has to be in start or an awake function;

And then you would notice that your instance was not a variable, you have to assign it like you did with the random value variable.

And you can just do cube_count++; to increment the variable by 1 :slight_smile:

var spawn : Transform[]; //array of spawn points
var game_cube : Rigidbody; //the game cube
var cube_count = 0; //cube counter

function Start () { //runs once at instantiation
InvokeRepeating("LaunchProjectile", 2, 3);
}

function Update() {
    if (cube_count>= 10) {
       CancelInvoke();
    }

}

function LaunchProjectile () {
    var randomPick : int = Random.Range(0,2);

    var instance = Instantiate(game_cube, spawn[randomPick].position, transform.rotation);
    instance.velocity = Vector3.zero;
    cube_count++;

}

How would you go about changing this code to make it so that a given spawn point can only have one Game Object spawn in it? EDIT: Also, spawn[randomPick] throws up the error stating that 'spawn' is undefined.

–