Beginner : Random gameobject from array

Hi all, I’m a very very beginner user I’m studing tutorials and reading all easy stuff I find about scripting. I’m trying to do some simple things to better understand about scripting. Now I wanted to do something simple like make a plane and a cube appear in a random way for some seconds and then be destroyed. I reached to do with just one object but i’m facing problem with arrays I guess even if I’ve read about it and searched for days cannot find my error. Unity says Object reference not set to an instance of an object (line 14 : aObjects.Add(plane):wink: but I don’t understand why. I attached the script to the main camera and set the cube and the plane in the scene as gameobject of the script in the main camera inspector. Any help would be higly appreciated. Thanks and sorry for my bad english and if it’s too dumb question :\

   var intervallo = 4;
private var prossimo = 0.0;

var aObjects = new Array();

var plane : GameObject;

plane = GameObject.Find("Plane");

var cube : GameObject;

cube = GameObject.Find("Cube");

aObjects.Add(plane);

aObjects.Add(cube);

function Update () {


if (Time.time > prossimo)
{
prossimo = Time.time + intervallo;

var clone = Instantiate(aObjects[Random.Range(0, aObjects.Length)], Vector3(0, 0, 0), Quaternion.Euler(270, 0, 0));

}

Destroy (clone, 3.0);

}

There are two things in your code that could cause you to get an “Object Reference Not Set” problem.

The first is if the array object “aObjects” is not actually pointing to a valid array object. It looks like you may have forgotten to call “aObjects = new Array()”. This will instantiate a new array instance, which you can then use to store objects. I’m a bit rusty with my Javascript, but I believe that saying “var aObjects : Array” is not enough.

Another reason you could get a problem like this is if GameObject.Find(“Plane”) is failing to find an object called “Plane” in your scene. Find() will return null if it can’t find anything, so trying to Add(null) might cause some problems.

Just solved… But please could someone explain me why??

Changed
var clone = Instantiate(aObjects[Random.Range(0, aObjects.Length)], Vector3(0, 0, 0), Quaternion.Euler(270, 0, 0));
to
var clone = Instantiate(aObjects[Random.Range(0, 2)], Vector3(0, 0, 0), Quaternion.Euler(270, 0, 0));

and it works. Any explaination would be appreciated :slight_smile: