- Home /
Random Spawn
I have this script
function spawn_cube ()
{
spawn_position = new Vector3(0,0,0);
var temp_spawn_cube = Instantiate(cube, spawn_position, Quaternion.identity);
}
function Update ()
{
spawn_cube();
}
but I wanted that my cube spawns randomly from 5 to 10 sec, not every second, what should I change or add to this to work.
Answer by Unity_gamer · Jun 29, 2015 at 02:12 PM
Hey,
you can implement your own custom timer to achieve this.Simple way to achieve this is by using Invoke function.
function Start ()
{
spawn_cube ();
}
function spawn_cube ()
{
spawn_position = new Vector3(0,0,0);
var temp_spawn_cube = Instantiate(cube, spawn_position, Quaternion.identity);
Invoke("spawn_cube",Random.Range(5.0, 10.0));
}
This is not tested , Check and post the result here.
It works, I tried with yield and it didnt worked but this works very well
But how can I relate spawn point to main camera? spawn_position = new Vector3(0,0,0);
Answer by sansol · Jun 29, 2015 at 03:58 PM
the easiest i can think about would be to have a variable (e.g. spawnTime) to store the new time were you want to spawn.
on start and inside spawn_cube, calculate the time you want to spawn adding randomly 5 to 10 seconds (spawnTime = time.time + system.random(5,10) ) or something like that.
on update, check if Time.time > than spawnTime.
hope i answered your question! :-)