I had to do add the last line of this code to avoid errors:
class nameOfClass {}
arrayOfObjects = new nameOfClass[//integer];
for (anObject in arrayOfObjects)
anObject = new nameOfClass();
Why is that? Without it, I still saw the same thing in the inspector, but apparently that was just some kind of allocation of memory, awaiting a real array of objects? I also wouldn’t have known to put the parentheses in (I did not make a constructor function). Unity told me it was looking for an opening parenthesis though, so I got it working.
I’ll take a stab at trying to explain (or guess) the problem.
When you create an array of “nameOfClass”, all you get is a bunch of pointers that are currently not pointing to anything. In a standard situation, you’d create an instance of “nameOfClass” by
anObject = new nameOfClass();
just like you did in that last line, and then add it to the array with
arrayOfObjects[×] = anObject;
This makes the pointer at position x in the array point to the anObject instance of “nameOfClass”.
If you try to access the variables of “nameOfClass” through the array without actually creating an instance of it, you’ll get "NullPointerException"s.
I hope this wasn’t too confusing. Let me know if this clears things up.
Thanks. I figured that was what was going on, but I’m not clear on why you would want an array full of empty pointers. I’m thinking, maybe it is faster to put the objects into memory later, if the memory space is already allocated?
(Sorry, I never had any real computer science training. I’ve been learning by the seat of my pants over the past year!)
You only “want” that when creating the array, which is generally followed immediately by filling the array with valid pointers. In your case you make the array (full of empty pointers) and then you jump right to trying to access things that aren’t there and thus, BONK!