-1

I can't figure out why it's telling me the object is null when I'm trying to fill the array with an object that I'm constructing.

public int size;
// Use this for initialization
public void Start()
{
    size = 10;
    Unit[,] array = new Unit[size,size];
    int i, j;
    for(i = 1; i<=size; i++)
    {
        for(j=0;j<size;j++)
        {
            if(i>=1&&j>=1)
            {
                array[i, j] = new Unit(array[i - 1, j].getHeight(), array[i, j - 1].getHeight());
            }
            else if(i>=1)
            {
                array[i, j] = new Unit(array[i - 1, j].getHeight(), 0);
            }
            else
            {
                array[i, j] = new Unit(0, 0);
            }
        }
    }
    for (i = 0; i <= size; i++)
    {
        for (j = 0; j <= size; j++)
        {
            Debug.Log(array[i,j].getHeight());
        }
    }
}

the Objects I am creating come from a constructor; Unit(int,int) It says line 23. I'm assuming that it means that the object doesn't exist in the the array but i'm creating the object so IDK

1 Answers1

0

Two erros that I see, the first is that the first for loop should be for(i = 0; i<size; i++) as c# is base 0. This would give you the null object because when you try to assign

if(i>=1&&j>=1)
{
    array[i, j] = new Unit(array[i - 1, j].getHeight(), array[i, j - 1].getHeight());
}

when i=1, array[0,j] was never assign (since i started in 1), so it's value is null.

The other is in the last group of loops, as the conditions should be the following:

for (i = 0; i < size; i++)
{
    for (j = 0; j < size; j++)
    {
        Debug.Log(array[i,j].getHeight());
    }
}

Because since C# is base 0, the indexes goes from 0 to size-1

Magnetron
  • 7,495
  • 1
  • 25
  • 41