- Home /
How to access a variable within a multidimensional array of class
Hi, I want to create a grid in which each element (position) will have multiple properties. I figured the best way to do it was to crate a class. But as it's going to be a 2D grid, I want to use that class in a 2D variable. Create the variable doesn't ssemto be a problem, but accessing the variables within always gives me errors... Here's the code:
class carteLayout
{
var terrain:int;
var terrainTemp:int;
var isroad:boolean;
var unit:int;
var blockTerrain:Transform;
}
var carte:carteLayout[,];
var grid:Transform;
var x:int;
var z:int;
function Start()
{
x = 20;
z = 20;
carte = new carteLayout[x,z];
CreateGrid(x,z);
}
function CreateGrid(newX:int, newZ:int)
{
carte = new carteLayout[newX,newZ];
for(var i = 0 ; i < newX ; i++)
{
for(var l = 0 ; l < newZ ; l++)
{
carte[i,l].terrain = 99;
carte[i,l].isroad = false;
carte[i,l].unit = 99;
Instantiate(grid,Vector3(i,0,l),Quaternion.identity);
}
}
}
I always get a NullReferenceException at the line "carte[i,l].terrain = 99"
Answer by whydoidoit · Sep 18, 2012 at 07:01 PM
When you made the array you just made a place to hold all of the class instances - you actually didn't put anything in there yet. I've added an initialiser to your code shown below:
carte = new carteLayout[newX,newZ];
for(var i = 0 ; i < newX ; i++)
{
for(var l = 0 ; l < newZ ; l++)
{
carte[i,l] = new carteLayout(); //Add this (and carteLayout should be named CarteLayout by convention)
carte[i,l].terrain = 99;
carte[i,l].isroad = false;
carte[i,l].unit = 99;
Instantiate(grid,Vector3(i,0,l),Quaternion.identity);
}
}
Also it would be good to make a constructor for the class, which will make setting up each array entry easier.
Wonderful ! That did it !
Also, Eric, I'm not familiar with constructors, I tried looking in the unity references, but did'nt find it. Can you tell me where to look ?
Thanks guys !
class Foo {
var a : int;
function Foo (a : int) {
this.a = a;
}
}
So ins$$anonymous$$d of:
var blah = new Foo();
blah.a = 42;
You can do:
var blah = new Foo(42);
I can see how it can be a faster way on the long run. I'll definitely try using that. Thanks Eric !
Answer by Khada · Sep 18, 2012 at 07:08 PM
Changing:
for(var l = 0 ; l < newZ ; l++)
{
carte[i,l].terrain = 99;
carte[i,l].isroad = false;
carte[i,l].unit = 99;
Instantiate(grid,Vector3(i,0,l),Quaternion.identity);
}
To:
for(var l = 0 ; l < newZ ; l++)
{
carte[i,l] = new carteLayout();
carte[i,l].terrain = 99;
carte[i,l].isroad = false;
carte[i,l].unit = 99;
Instantiate(grid,Vector3(i,0,l),Quaternion.identity);
}
should fix your problem.
Also, remove:
carte = new carteLayout[x,z];
from your start function and also remove:
x = 20;
z = 20;
if you want to use the values you define in the unity editor.
EDIT: Sigh, late to the party.
Good point ono the Start() function - definitely worth the OP doing that...