system
1
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
BiG
2
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.
save
3
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 know it is a very old post. But for anyone wanting to call a function repeatedly InvokeRepeating can be used.
// Waits 2 seconds, then calls the function named SpawnObject every 1 second until canceled
InvokeRepeating(nameof(SpawnObject), 2f, 1f);
To stop calling the function just use:
CancelInvoke(nameof(SpawnObject));