C# Global Dynamic Arrays

Hi, I’m new to C# and general OOP, and I’m having some difficulty understanding the dynamic arrays.

I have two scripts, one called GridDeclare and one called GridSpawn. It’s necessary that they’re separate scripts.

Within GridDeclare I want the ability to adjust the grid size, so within my GridDeclare class I’ve used:

public int xsize = 10;
public int zsize = 10;

Which can obviously be modified within the Object Inspector.

Then I want to introduce my grids themselves.

public static int[,] grid;
public static int[,] run;
public static bool[,] runvalid;

However, I want them to be of size [xsize,zsize]. So within my Start() function I declared:

int[,] grid = new int[xsize, zsize];
int[,] run = new int[xsize, zsize];
bool[,] runvalid = new bool[xsize, zsize];

I then used Streamreader to read a tab delimited text file into my grid array.

I then analysed the data to fill in my run and runvalid tables.

Next I wrote a bunch of scripts which, upon enabling, will are meant to read in the run and runvalid arrays and edit them, and then save them again.

But obviously I’ve initialised them as just standard variables within my Start function, so I just get a NullReferenceException: Object Reference not set to an instance of an object.

So I’m left with a dilemma, in that I want to create a global array that I can adjust the size of at runtime, access from other scripts and save to, and the only way I can think of doing it right now is a really sloppy workaround where’d I’d save the array data to a text file every time I modify it and read it in every time I access it. Any tips?

Your answer may lie here: http://unity3d.com/support/documentation/ScriptReference/Array.html

Using this type of array, basically to resize it means copying it to another array with the new size (then back again I would presume).

Looks like you may have declared two sets of variables named grid, run, and runvalid.

Try changing your Start() function from this:

int[,] grid = new int[xsize, zsize];
int[,] run = new int[xsize, zsize];
bool[,] runvalid = new bool[xsize, zsize];

To this:

grid = new int[xsize, zsize];
run = new int[xsize, zsize];
runvalid = new bool[xsize, zsize];

Otherwise, you’re actually creating an entirely new set of variables which unfortunately happen to have the same name, type, and general behavior… but which also effectively stop existing at the end of that one code block.

(Wikipedia’s article on variable scope has a little more explanation, if you’re curious.)