- Home /
Random Delay time
I'm trying to set up some falling objects in a 2d view, right now they fall and respawn fine, but I'm trying to get a few 'special' ones to fall after a random delay between 5-20 seconds each. How would I go about achieving this? I know how to use the Random.Range, but how would I apply this to a delay timer?
This is my delay code:
var objectSpeed: int;
var delay = .5; var timer = 0.0;
function Update () {
timer += Time.deltaTime;
if (timer >= delay){
amtToMove = objectSpeed * Time.deltaTime;
transform.Translate(Vector3.down * amtToMove); //timer = 0.0;
}
Any help would be appreciated.
Answer by Eric5h5 · Oct 26, 2010 at 07:53 PM
var objectSpeed: int; var minWait = 5.0; var maxWait = 20.0;
function Start () { yield WaitForSeconds(Random.Range(minWait, maxWait));
while (true) {
transform.Translate(-Vector3.up * objectSpeed * Time.deltaTime);
yield;
}
}
Note that Vector3.down is undocumented/deprecated; you should use -Vector3.up instead.
Ok, that seems to work.. sort of. Inside of the while statement, I placed an if statement so that if the object reached a height, its position will reset to where it was before. The only problem now is that it ignores the delay after it drops one time. How can I make the delay work each time?
@$$anonymous$$: if I understood correctly, enclose all the code in the Start function in a "`while (true)`" loop, and with your if statement, use some condition other than "true" so that the inner while loop ends appropriately. (Or at least use break
so that you break out of the inner loop when needed.)
Actually, I just copied the yield line into the if statement, and it did the trick. Thanks for the help.
Answer by AliAzin · Oct 26, 2010 at 05:08 PM
You can simply use yield structure before respawning :
// before respawning do this :
yield WaitForSeconds(Random.Range(5,20));
//respawning