- Home /
random range spawntime
Okay how do I make it so that the TIME between an object spawning is random? Here's my script
var evilsphere : Transform; var waitTime = 1.0;
function Start () { InvokeRepeating ("Spawn", waitTime,Random.Range(1,10));
}
function Spawn () { Instantiate (evilsphere, transform.position, transform.rotation);
}
As you can see I tried using Random.Range but that just made the wait time longer.
Answer by Mike 3 · Jul 20, 2010 at 04:56 PM
You can use a coroutine to do it, like this:
var evilsphere : Transform; var minWait = 1.0; var maxWait = 10.0;
function Start () { while(true) { yield WaitForSeconds(Random.Range(minWait, maxWait)); Spawn(); } }
function Spawn () { Instantiate (evilsphere, transform.position, transform.rotation); }
Or if you want to make it even shorter for the fun of it:
var evilsphere : Transform; var minWait = 1.0; var maxWait = 10.0;
function Start () { while(true) { yield WaitForSeconds(Random.Range(minWait, maxWait)); Instantiate (evilsphere, transform.position, transform.rotation); } }
Just for the sake of explaination - the InvokeRepeating function is only called once, so you're telling it to invoke the first time after waitTime seconds, then to repeat it every x (number returned from random.range) seconds. There isn't a way to tell it to change it every call without stopping it and restarting it each time
Your answer
Follow this Question
Related Questions
InvokeRepeating with a variable? 2 Answers
NullReferenceException: Object reference not set to an instance of an object 2 Answers
Timed event Question 2 Answers
Mulitple spawn points with random seed. 3 Answers