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?