Array has length but is null?

I have a weird problem. I am using a editor window. With this window I am generating an array of enemies. The array I’m using is the Unity’s built-in array.

Here is the simplified version of my code:

class Enemy {
         var health : int;
}

var enemies : Enemy[];

enemies = new Enemy[5];

// assign a value to one of array's elements    
enemies[0].health = 10;

In the last line I get an error that says object reference is null. I used debug.log and printed a message if array is null. And another message telling array’s length.

It seems that the array is null, but it does return enemies.length as being “5”. In the inspector I can see there are 5 elements, but the values are not assigned.

But when I assign each element one by one:

for(i=0; i<5; i++)
{
    enemies *= new Enemy();*

}
It works properly.
What am I missing? Why doesn’t this work. Util now I had not run into such an issue. This code is inside an objects script, I call it from my custom window BUT, it also doesn’t work when I call it from object’s script in runtime.

The variable enemies is a reference to an array. Because it’s a reference, it could point to null, or it could point to an array which will have some length.

Each index in enemies is also a reference, this time to an Enemy object. Once again, each of those references could be null, or it could point to some Enemy.

Whenever you have a chain of references, it’s important to remember that any reference in that chain might be null. This is a cause of many, many issues in programming.

It may help to draw some of the data structure.

First, we declare a variable, enemies:

var enemies : Enemy[];

At this point, we have a null named enemies:

enemies --> null

Second, we create an array:

enemies = new Enemies[5];

This creates an array, but doesn’t populate it with anything:

enemies --> +---+--------+
            | 0 | null   |
            +---+--------+
            | 1 | null   |
            +---+--------+
            | 2 | null   |
            +---+--------+
            | 3 | null   |
            +---+--------+
            | 4 | null   |
            +---+--------+

Third, you populate the array:

for(i=0; i<5; i++)
{
    enemies *= new Enemy();*

}
Now, each reference in the array points at something:
enemies → ±–±-----------+
| 0 | Enemy #1 |
±–±-----------+
| 1 | Enemy #2 |
±–±-----------+
| 2 | Enemy #3 |
±–±-----------+
| 3 | Enemy #4 |
±–±-----------+
| 4 | Enemy #5 |
±–±-----------+
With practice, all three steps will become second nature, but it is important to understand that they are three separate steps.
If you find all of this confusing, you can also use a collection such as a List, which automatically re-sizes when adding members. Arrays are very fast, but sometimes not very friendly.