- Home /
Call a function multiple times
Hi, I'm wondering if there is something I'm missing here.
Is there a fast, and easy way to call my function "Spawn" from the start menu 3 times (using the amount variable)?
Seems like this should be obvious but I can't figure it out. Here's the code.
//Objects To Spawn
var objectsToSpawn : GameObject[];
//Spawn Locations
var spawnLocations : Transform[];
//spawn amount
var amount = 3;
function Start() {
Spawn(amount);
}
function Spawn() {
//Select From Objects To Spawn
var thingToSpawn : int = Random.Range( 0, objectsToSpawn.length );
//Select From Spawn Locations
var placeToSpawn : int = Random.Range( 0, spawnLocations.length );
Instantiate( objectsToSpawn[thingToSpawn],
spawnLocations[placeToSpawn].position,transform.rotation);
}
I'm trying to call the spawn function 3 times. Any ideas where I can stick the var amount (if anywhere)?
Thanks
Answer by BiG · Jan 27, 2012 at 12:34 PM
This is how your Start function should be:
var amount = 0;
function Start(){ for (amount=0; amount<3; amount++) Spawn(); }
Watch out: I cannot say if the rest of your code is correct (even because you have not formatted it properly): this is simply the logic behind calling a function 3 times as the application starts.
$$anonymous$$any thanks, The spawn function works fine. It basically selects (randomly) between several spawn locations, then selects (again, randomly) between several prefabs and then instantiates the prefab at the position.
It's a nice way to make a cheap L4D director style item placement. Again, thanks for this, much appreciated
Answer by save · Jan 27, 2012 at 12:38 PM
You can use a loop to iterate through the amount,
function Spawn (quantity : int) {
for (var i : int = 0; i<quantity; i++) {
//Select From Objects To Spawn
var thingToSpawn : int = Random.Range( 0, objectsToSpawn.length );
//Select From Spawn Locations
var placeToSpawn : int = Random.Range( 0, spawnLocations.length );
Instantiate( objectsToSpawn[thingToSpawn], spawnLocations[placeToSpawn].position,transform.rotation);
}
}
You could also pass more variables to the function, to switch objects or so:
function Spawn (quantity : int, thing : GameObject) {}
I have just ninja'd you, @save! ;) but your explanation is much more complete, with respect to the OP's request.
+1