Multidimensional Arrays of Classes in Java

I am attempting to create a simple Cube/Sauerbraten/Minecraft-style game as practice with using Unity. I can’t work out how to create a multidimensional array of classes. The following code is what I’m using at the moment, but it just keeps getting a null reference exception:

public class CubeClass {
	public var cubematerial : byte; //0=air, 1=solid
	public var cubeobject : GameObject;
}

public var WorldSize : int=256;
var Cube : CubeClass[,,];
for(var z : int=0;z<WorldSize;z++) {
	for(var y : int=0;y<WorldSize;y++) {
		for(var x : int=0;x<WorldSize;x++) {
			Cube[x,y,z]=new CubeClass();
		}
	}
}

Also, why can’t I just type

for(int z=0;z<WorldSize;z++) {

I’m new to Java so I may be missing something but I read a tutorial on Java in general and it said you could do it that way, so why doesn’t it work in Unity?

Thanks,
David

First of all you have to actually create the array. I’m not sure if you can do this in UnityScript (JavaScript). I can remember that there was a problem with multidimensional array in UnityScript, but i’m not sure if they fixed it. In C# you would create the array like this:

// C#
CubeClass[,,] Cube;  //variable declatarion
Cube = new CubeClass[WorldSize ,WorldSize ,WorldSize];

Arrays have a fix size. The size has to be specified when the array is created.

Second, UnityScript is based on Javascript, not Java.

Third, this line: for(int z=0;z<WorldSize;z++) would be valid C# code, but not UnityScript. Variable declarations in Javascript always needs the var keyword.

In a nutshell, Java and JavaScript are not the same language.

Declaring an int in Java:

int x;

Declaring an int in UnityScript (Unity’s custom implementation of JavaScript):

var x : int;

The meaning is more or less the same, but the syntax is different. That’s why your for loop looks different.

From there, you’re declaring an array named Cube, but not actually creating it. Before accessing the array, you’ll need something like this:

Cube = new CubeClass[WorldSize, WorldSize, WorldSize];

If you access the array before then, you’ll get a NullReferenceException.