I have a class, which inherits from MonoBehaviour, which includes a member array declared like so:
If I create a new GameObject (in the editor) and assign this script to it, that array appears in the inspector with a default length of 0, as you would expect.
I also have a custom EditorWindow which contains controls that let me act on the contents of that array, for whichever GameObject is selected. One such control creates a new EventNodeInfo and appends it to the array.
If I create a new GameObject, assign my script, open my custom EditorWindow and click that "add" control, I get a null reference exception when I attempt to dereference "Length" out of the array reference on the newly-created object. The inspector shows this zero-length array just fine, but from my EditorWindow's perspective the array appears as null.
Now for the really weird part: if I touch a script (no changes to its content, just force-recompile), that new object's array is suddenly, magically okay! I can edit it through my custom EditorWindow as I would expect: the reference to the still-zero-length array is no longer null, and the world rejoices.
So um... what am I missing? O_o
asked May 15 '10 at 11:16 PM
You're missing initialization of your array. Arrays are not magic, you cannot just resize them however you'd like. You have to instantiate them with a set size, and then go from there. Unity's Inspector just handles a lot of the hard work for you in terms of resizing an array, and it might be instantiating it for you even, I'm not sure.
You have two options. Either initialize your array, or use a List<> (which supports dynamic resizing).
You need something like this in Start() or Awake():
or whatever size you want your starting array to be. Each item is then filled in with a null value until you instantiate it.
You could also use a List<> generic, though I don't know how well those are supported by the Unity Inspector.
See the List documentation on MSDN for more information about Lists (which are vastly superior to arrays).
answered May 16 '10 at 12:18 AM