array index out of range when assigning a material to the render from an array

hi all,

I have the following code…

int billboardsMaterialIndex = Random.Range (0, billboardMaterials.Length);
			Instantiate (billboard, new Vector3(billboardPosition.x,billboardPosition.y,billboardPosition.z), Quaternion.Euler (0,180,0));
			billboard.renderer.material = billboardMaterials[billboardsMaterialIndex];

the code instantiates a clone of a prefab at a point relative to procedurally generated scenery.
This part works fine.

I want to mix up the textures on my cloned prefabs so I added a material array and I am trying to add a random material from the array onto the newly instantiated clone of my prefab.

I get IndexOutOfRangeException: Array index is out of range. on the line which says:

billboard.renderer.material = billboardMaterials[billboardsMaterialIndex];

billboardsMaterials is an array. declared like so:

public Material[] billboardMaterials

The array has 2 element (0,1) and is made up of materials with textures attached to them. they were placed into the array by dragging them across into the inspector.

billboardsMaterialIndex is just a counter to hold the random number selected between 0 and the arrays length.

I don’t understand why I am getting index out of range errors.

I have tried changing the line

billboard.renderer.material = billboardMaterials[billboardsMaterialIndex];

to

billboard.renderer.material = billboardMaterials[0];

because I know that element 0 holds a material but I get the same error.

Any help would be appreciated.

Sounds like you need to declare the length of the array in the definition, if you know how big it should be.

If you wish to populate it on the fly, you could resize it

//Javascript

 System.Array.Resize.<int>(billboardMaterials, billboardMaterials.Length + 1 );

Edit :

Are you absolutely sure that the materials are linked on the original object/ prefab? If they are populated by script during runtime this will also be the case on the clone.