two-dimensional array

I know I’m probably gonna ask a stupid question, but I haven’t been able to figure it out for hours. The bottom line is this: I want to implement code that will be responsible for whether you can move the grid up or down using a two-dimensional array.First I define variables and write code in the Start method that initializes the array. Where 0 means free, 1 means busy:

public int h = 10, w = 10;
    public int[,] grid;
    public int x,y;
   
    void Start()
    {
        for (int i = 0; i <= h; i++)
        {
            grid[i,w] = 0;
            Debug.LogWarning(grid[i,w].ToString());           
            for (int j = 0; j <= w; j++)
            {
                grid[h,j] = 0;
                Debug.LogWarning(grid[h,j].ToString());
            }
        }
        grid[x,y] = 1;
    }

Next, I define a method that hangs on the button and checks if the adjacent cell is busy:

public void moveon()
    {
        for (int i = x; i <= h; i++)
        {
            Debug.LogWarning(grid[i,w].ToString());
            if(grid[i,w] == 0)
            {
                x = x + 1;
                gridup(x);
            }
        }
    }

If it is free, the following method is called, which overrides the array with the new values 1 and 0:

public void gridup(int h)
    {
        for (int i = 0; i <= h; i++)
        {
            grid[i,w] = 0;
           
            for (int j = 0; j <= w; j++)
            {
                grid[h,j] = 0;
            }
        }
        grid[x,y] = 1;   
    }

After I press the button during the game, I get the following error:

NullReferenceException: Object reference not set to an instance of an object
GridControl.Start () (at Assets/GridControl.cs:18)

What’s wrong with my way?

Where is the array being initialized? Arrays are initialized to a fixed size, which Unity kind of makes confusing because when you make a serialized array that shows up in the inspector, it lets you set the size arbitrarily there and not have to worry about initializing it to any size in your MonoBehaviour class. Multidimensional arrays aren’t serialized, so it isn’t showing up in the inspector, and so Unity isn’t setting the size for you based on it.

In order to use grid, you need to first set it to grid = new int[h, w];

Note that if you only have two settings, off/on, busy/okay, 0/1, you may want to just use bools instead, as they’re smaller and cheaper.

1 Like