Ok, so I’ve been trying to learn this stuff all day but nothing seems to work well. I have over 20 test scripts with the beginning title of RandomSpawn. 
I have about 10 objects. I want them to spawn in a random order. And they need to spawn at random times. BUT, it can’t be random enough that it can spawn in a matter of milliseconds and collide with a previous spawn.
This is what I’ve got so far.
var Car001 : GameObject;
var Car002 : GameObject;
var CarDecider = 0;
var WaitTime = 0;
var StartSpawn = false;
function Update () {
if (StartSpawn == false) {
CarDecider = 1 + (Random.value);
WaitTime = 1 + (Random.value);
StartSpawn = true;
}
if ( CarDecider > 1.5) {
Invoke ("SpawnCar001", WaitTime);
CarDecider = 0;
}
if ( CarDecider < 1.5) {
Invoke ("SpawnCar002", WaitTime);
CarDecider = 0;
}
}
function SpawnCar001 () {
clone = Instantiate(Car001, transform.position, transform.rotation);
}
function SpawnCar002 () {
clone = Instantiate(Car002, transform.position, transform.rotation);
}
All it does is spawn Car002 infinity. Any idea how to fix this?
Hi,
I i rewrote your script the way i would but haven’t tested it, though it should work if there aren’t any typos lol.
//Minimum time to wait before spawning a random object (in seconds)
var min_wait_time = 0.5;
//max time to wait before spawning a random object (in seconds)
var max_wait_time = 10.0;
//We will use a array of game objects and assign them in the editor
var obj : GameObject[];
var start_spawn = false;
function spawn_random_object(id,wait_time)
{
//Wait for wait_time
yield WaitForSeconds(wait_time);
//Spawn obj
clone = Instantiate(obj[id], transform.position, transform.rotation);
}
function Update()
{
if(start_spawn == true)
{
/*
Call the spawn function with the id set to a random number between 0 and the length of the obj array -1 (since arrays start at 0)
Then set the wait_time to a random float number between the min_wait_time and max_wait_time (Note: We add0.1 because the max in random.range
is exclusive and in order to get the max value as a result the max must be greater.
*/
Spawn_Random_Object(Random.Range(0,obj.length)-1,Random.Range(min_wait_time,max_wait_time + 0.1))
}
}
Update runs every frame; you should stay away from it unless you have code that you literally want to run every single frame, which is definitely not the case here. Also:
var CarDecider = 0;
var WaitTime = 0;
This makes these variables into integers, so
CarDecider = 1 + (Random.value);
will always result in 1. Either specify floats explicitly or use 0.0 instead of 0.
Also, whenever you have more than one object of a similar type, use an array, not a collection of single variables.
var cars : GameObject[];
var minWaitTime = 1.0;
var maxWaitTime = 5.0;
function Start () {
while (true) {
yield WaitForSeconds (Random.Range(minWaitTime, maxWaitTime));
Instantiate (cars[Random.Range(0, cars.Length)], transform.position, transform.rotation);
}
}
–Eric
ok! its all sorted out! Thank you guys sooo much. INTERNET HUUUG!!!