array problem how to solve it?

hi,

i declared this array

//ARRAY OF LABELS
var MicroLabel : CLabel[];

CLabel is custom class that holds information about the labels size, width and height and some other
data. it has constructor and when i need just one i create it like this: var Label : CLabel =new Clabel(230,30);

but when i try to initialize the array of the labels like this:

[LEFT]for(i=0;i<children.length-1;i++){
	
       MicroLabel[i]=new CLabel(230,30);
	
}[/LEFT]

i get the error “Array index out of range”

also i tried this way

MicroLabel = new CLabel[children.length-1];

and try to initialize it like this:

MicroLabel[0].rWidth=230;

i get the this error: Null reference exception : Object reference not set to an instance of the object
in the line where i try to initialize the MicroLabel[0].rWidth

does any body have the idea how to solve it?
i dont know the exact size of the array so it has to resizable, array’s are confusing, i might add…

thanks!

var MicroLabel : CLabel[ 10 ];

Youre creating a null array, you have to allocate them memory.

Try MicroLabel = new CLabel[10]; // Create an array of 10 CLabels

Although if youre wanting to add you might want to look at dynamic containers.

when i put this:

var MicroLabel : CLabel[3];

i get this error : “;” expected, insert semicolon at the end

what is wrong?

You must have to new it. I dont use JS so im not sure how it behaves in comparison to C#. Try:

var MicroLabel : CLabel[ ];

function Start()
{
MicroLabel = new CLabel[10]; // Create an array of 10 CLabels
}

var MicroLabel : CLabel[] = new CLabel[children.length - 1];

for (int i = 0; i < children.length; i++)
{
	MicroLabel[i] = new CLabel(230, 30);
}

//then you can have calls like:
MicroLabel[0].rWidth = 230;

FizixMan has it right, but to clarify -

var MicroLabel : CLabel[]

– Creates a CLabel array with no data whatsoever. Any attempt to read it is a null exception.

var MicroLabel : CLabel[] = new CLabel[10];

– Creates an array of ten CLabel pointers. They are null. You can call MicroLabel, but attempting to read members of that variable (MicroLabel[×].whatever) before you initialize it results in a null exception.
That is, you could -

if ( MicroLabel[X] ) MicroLabel[X] ++;
else Debug.Log( X + " element not initialized!");

The problem was that you hadn’t initialized the CLabels after creating space for them -

MicroLabel[i] = new CLabel(230,30)

– initializes the ith element of MicroLabel, so now it actually points to something and can be used as expected.