- Home /
built in array in class
I must be doing something wrong as far as using built in arrays in classes. Here is my test code:
class DemoData
{
var x : float;
var y : float;
var z : float;
var name : String;
}
public var _iUsersTest:DemoData[] = new DemoData[3]; //this works!
class UserData
{
public var _iUser : DemoData = new DemoData(); // this works!
public var _iUsers : DemoData[] = new DemoData[3]; // this does not!
function UserData() { }
}
private var myData : UserData;
function Awake ()
{
myData=new UserData();
myData.iUsers[0].name = "fred"; //throws NullReferenceException error
}
So _iUsers throws and NullReferenceExeption any time I try to set any of its elements, but the same syntax outside a class works just fine. How do I make _iUsers work?
Answer by syclamoth · Dec 03, 2011 at 11:32 PM
The problem here is that while the array has been initialised with a length, none of its members have! So, at this point it's a 3-long array filled with null objects. Now, there are a few ways to get around this- one way is to make DemoData a struct, instead of a class- structs can never be null, they simply automatically initialise with default values. They are also treated as value objects, not reference objects.
Another way would be to automatically fill _iUsers in the constructor for UserData-
function UserData() {
for(var i : int; i < _iUsers.Length; i++)
{
_iUsers[i] = new DemoData();
}
}
This guarantees that there will be objects in every slot of the array at the start.
I can understand where the confusion would arise- if you put an array in the base class (technically deriving from MonoBehaviour, but you can't see that because grr javascript grr), Unity automatically serializes and fills it so that it can be seen in the inspector. However, this is not functionality provided by the array itself, rather magic contained in the MonoBehaviour base class. If myData were public, the magic would extend to it as well- but since it's private, the Inspector can't see it, and doesn't serialize it.
Thanks for the answer and thanks even more for the great explanation. Probably saved me from drawling the wrong conclusion from all of this. Did not consider the now obvious fact that things in the inspector get initialized and set.