- Home /
Why Does Initialising Built-In Array of Classes Require Constructor?
Say I have the following short script:
#pragma strict
class myArrayInfo
{
var name:String;
}
static var myArray:myArrayInfo[];
function Start()
{
myArray=new myArrayInfo[3];
myArray[0].name="Random name 1";
myArray[1].name="The answer to the ultimate question of life, the universe, and everything is...";
myArray[2].name="...42.";
}
I would expect that to work, but I get NullReferenceException: Object reference not set to an instance of an object
at line 13, where I attempt to set index 0 of the array.
So I tried doing this:
#pragma strict
class myArrayInfo
{
var name:String;
function myArrayInfo(){}
}
static var myArray:myArrayInfo[];
function Start()
{
myArray=new myArrayInfo[3];
myArray[0]=new myArrayInfo();
myArray[1]=new myArrayInfo();
myArray[2]=new myArrayInfo();
myArray[0].name="Random name 1";
myArray[1].name="The answer to the ultimate question of life, the universe, and everything is...";
myArray[2].name="...42.";
}
And this works. But why?! Why is it necessary to make it run an empty function (the constructor) to be assigned a value? The constructor clearly isn't doing anything, unless I'm completely misunderstanding how constructors work.
Why is it necessary to make it run an empty function (the constructor)
It's not; get rid of that. It doesn't serve any purpose. You only need a constructor if you want to assign values when creating an instance.
@Eric5h5 Then how do I make the code work? As I said, without using an empty constructor on each element it gets a NullReferenceException
.
Just initialize the variables in the array, since they are null until initialized.
var myArray = new $$anonymous$$yClass[5];
for (item in myArray) item = new $$anonymous$$yClass();
An empty constructor doesn't do anything, so it should be removed.
@Eric5h5 :O WOW, ok. I didn't know you could do that! I never knew you could do new $$anonymous$$yClass()
without actually defining a constructor! Learn something new every day...
Answer by steakpinball · Oct 27, 2014 at 01:41 PM
The constructor primarily gets a memory location for a new object. It optionally also initializes the object.
When creating an array of objects the array is initialized with all null references ( 0x0000000
). You need to call the class's constructor to get a valid memory location and therefore an object. Primitive types work a little differently in that you don't need to call a constructor for it to be in memory since they are value types.
An example: If you had
var info : myArrayInfo;
info.name = "Name";
it would return an error since the constructor has not been called.
Huh, I never realised the constructor did more than just initialise the member variables. I call myself a good programmer and then I have to ask questions like these. *facepalm* (argh I hate Unity Answers' website! I can't even escape the asterisks like on SE sites!)