x


Member arrays not initialized in editor until after scripts are recompiled

I have a class, which inherits from MonoBehaviour, which includes a member array declared like so:

public EventNodeInfo[] m_eventNodeInfo;

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

more ▼

asked May 15 '10 at 11:16 PM

invicticide gravatar image

invicticide
232 6 10 12

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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():

m_eventNodeInfo = new EventNodeInfo[10];

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.

List<EVentNodeInfo> m_eventNodeInfo = new List<EVentNodeInfo>();

See the List documentation on MSDN for more information about Lists (which are vastly superior to arrays).

more ▼

answered May 16 '10 at 12:18 AM

qJake gravatar image

qJake
11.6k 43 78 161

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1679
x1363
x349
x171
x69

asked: May 15 '10 at 11:16 PM

Seen: 2133 times

Last Updated: May 15 '10 at 11:16 PM