- Home /
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";
}
Answer by Eric5h5 · Feb 28, 2013 at 06:51 PM
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#.
Answer by Mikilo · Feb 28, 2013 at 06:47 PM
Hi!
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.
Didn't work.
I don't understand what I'm doing different from the Unity example:
// Exposes an float array in the inspector,
// which you can edit there.
var values : float[];
function Start () {
// iterate through the array
for (var value in values) {
print(value);
}
// Since we can't resize builtin arrays
// we have to recreate the array to resize it
values = new float[10];
// assign the second element
values[1] = 5.0;
}
Eric is right. Thank to point that out.
Anyway, don't forget that new with [] will only allocate a container, not the content!
And in C# when you initialize names = new GUIText[3]; it will allocate memory for 3 new guiTexts so it isn't necessary to go through each element manually.
This is incorrect. You still need to actually create the GUIText objects. $$anonymous$$erely creating an array will not do this, in any language. See my answer.
I don't understand what I'm doing different from the Unity example
Primitive types (and structs) don't need to be created separately, since they have a default value. GUIText does not have a default value, other than null, so it must be created.
Why does this throw a NullReferenceException then?
private var names:GUIText[];
function Start()
{
names = new GUIText[3];
names[0] = new GUIText();
names[0].text = "alsdkf";
}