- Home /
yield WaitForSeconds to delay the instantiation of a game Object;
I have an empty GameObject That Randomly selects a prefab out of 3 and then instantiates it, this works fine and it is always random, the problem is that it instantiates the next object immediately after the previous one, how do make so that there is a random amount of delay time before each object is instantiated. Help would be greatly appreciated.
Here is the Script attached to the empty Game Object;
var Cube1 : GameObject;
var Cube2 : GameObject;
var Cube3 : GameObject;
function Update()
{
var Delaytime: int = Random.Range(0,5)
yield WaitForSeconds(Delaytime);
var RandNum : int = Random.Range(1,4);
print(RandNum);
if(RandNum == 1) { Instantiate (Cube1,transform.position, transform.rotation); }
if(RandNum == 2) { Instantiate (Cube2,transform.position, transform.rotation); }
if(RandNum == 3) { Instantiate (Cube3,transform.position, transform.rotation); }
}
Format code by selecting it and hitting the code button, please.
Answer by Eric5h5 · Apr 10, 2011 at 11:45 PM
Update runs every frame. Only use it if you want something to happen every single frame. Since you're trying to use a delay with yield (which you can't do in Update--see above), that means you don't want Update, since you want something to happen only sometimes. Also, using multiple separate objects is a big pain compared to just using an array. Code is easier to understand if you follow the convention of using camelCase for variable names, and Uppercase for function/class names. Probably you don't want to use 0 as a possibility for the number of seconds to yield, because you'd spawn multiple objects simultaneously sometimes.
var cubes : GameObject[];
function Start() { while (true) { yield WaitForSeconds (Random.Range (1.0, 5.0)); Instantiate (cubes[Random.Range (0, cubes.length)], transform.position, transform.rotation); } }