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?
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:
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.