Instantiate Objects using Random? Scripting question...

Hi Everybody,

I am still in the trial period of Unity, but am having so much fun with it I’ll be purchasing it for sure!

I’ve never done any programming before this, so I have a lot of questions about the scripting. So far I’ve been able to get quite a few things happening in my little game I’m making, but have hit a few stumbling blocks I could use help with. I am a professional sound designer, so perhaps if someone has general sound design questions I could be usefull that way and reciprocate if someone can give me a few tips with the scripts.

I have a script to instantiate a sphere every few seconds from an empty game object. The sphere then flys toward the camera. This is working fine, but I would like to make several spheres that get randomly selected, so sometimes sphere 1 comes out, sometimes sphere 2, etc. Also, I would like the timing to vary so its not just every 3 seconds, but between 3-10 seconds. Here is what I am using now:

var newObject: GameObject;

function Start() {
while (true) {
yield WaitForSeconds(3);
Instantiate(newObject, transform.position, transform.rotation);

}
}

I know this is probably simple to do, but I am still trying to get a grasp on programming, so if anyone could give me some tips that would be great.

Thanks!

Matt

Arrays to the rescue!

a_spheres = GameObject[]; //array of game objects populated from the Inspector

function Start() {
    var go_selected : GameObject;
    go_selected = a_spheres[Random.Range(0,(a_spheres.length - 1))]; select a random index from the array and pass it to a new var
    while (true) { 
        yield WaitForSeconds(3); 
        Instantiate(go_selected, transform.position, transform.rotation); 
    } 
}

Thanks for the reply!

I couldn’t get this code to go, I got this error message from Unity:

“Type ‘System.Type’ does not support slicing.”

Is what you wrote the JavaScript slice Method?

The variable needs to be defined correctly. When using Random.Range with integers, the upper range is non-inclusive. Also you’d want to pick a different one every time, not pick a random one and then just instantiate that one always. Should be:

var a_spheres : GameObject[]; //array of game objects populated from the Inspector 

function Start() { 
    while (true) { 
        yield WaitForSeconds(3.0); 
        Instantiate (a_spheres[Random.Range(0, a_spheres.Length)], transform.position, transform.rotation); 
    } 
}

–Eric

Thats awesome, its works! Thanks guys, this is really useful.

Matt