- Home /
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
Answer by qJake · May 16, 2010 at 12:18 AM
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).
Your answer
Follow this Question
Related Questions
Any way to attach a bit of code to individual UI Windows [Editor] 1 Answer
Custom Prfab Editor Window 0 Answers
What is the best way to draw icons in Unity's Hierarchy window? 1 Answer
How do I code my own custom built blend tree node as seen in the Animation Controller Editor Window? 1 Answer
Editor Window Views 0 Answers