NullReferenceException with Javascript Array

I’m learning Javascript, normally use C#. I get a NullReferenceException with defining the names of my GUIText array in the Start Function. I’m not initializing the array right. Thanks for the help. And don’t tell me to assign it in the inspector. I can get it to work that way, but I need to understand why I cannot initialize it in code.

private var buttons:GUITexture[];
private var names:GUIText[];

function Start()
	buttons = new GUITexture[3];
	names = new GUIText[3];
	names[0].text = "APlane";
	names[1].text = "BPlane";
	names[2].text = "CPlane";

You created the array, but you didn’t initialize any of the entries.

names[0] = new GameObject("", GUIText).guiText;
names[0].text = "APlane";

This isn’t anything to do with Javascript, by the way; the exact same thing applies to C#.


I don’t know the exact behavior in JS, but I assume it is same as C#.

When you allocate an array of element, you only allocate the array, not the element!

In your case, you need to do:

this.names = new GUIText[3];
this.names[0] = new GameObject("", typeof(GUIText)).guiText;
this.names[1] = new GameObject("", typeof(GUIText)).guiText;
this.names[2] = new GameObject("", typeof(GUIText)).guiText;
// And do your stuff after.

Good luck.

Edit: With the corrected code.