- Home /
How to Make 2 dimension array of classes
i have the following class
using UnityEngine; using System.Collections;
public class Tile_Info { int ID; int Varriation; }
i would like to access it using simillar to this
maparray[0,0].tile_id=0
can someone place the code here to help me figure out how to do this please
duck is right. i just want to say. use a private array inside your tile class for your tiles and change your design method.
Answer by duck · Feb 15, 2010 at 09:57 PM
First I'm changing the names slightly to adhere to Unity (and c#) coding conventions. These aren't errors but it's good to stick to:
"Tile_Info" becomes "TileInfo"
"maparray" becomes "map"
"Varriation" becomes "variation"
Now, declare the array like this:
TileInfo[,] map = new TileInfo[width,height];
Next, make sure you populate the array cells with instances of TileInfo, using something like this for each cell which contains a tile:
// fill out the empty array with TileInfo instances:
for (int x=0; x<width; ++x) {
for (int y=0; y<height; ++y) {
map[x, y] = new TileInfo();
}
}
Then you can use the array like this:
TileInfo thisTile = map[x,y];
thisTile.ID = someValue;
thisTile.variation = someValue;
Or directly access the tile's variables:
map[x,y].ID = someValue;
map[x,y].variation = someValue;
And the same for testing:
if (map[x,y].ID == someValue) { ... }
hope this helps!
Don't forget that you have to initialize each element in map before you use them, as such map[x, y] = new TileInfo(); Built-in arrays use default(T) to initialize the array elements, and for reference types that is null.
well i tried this but i am a bit confused
using UnityEngine; using System.Collections;
public class TileInfo { public int Tile_ID; public int Tile_$$anonymous$$od; }
public class Tile_$$anonymous$$ap {
public static TileInfo[,] map = new TileInfo[32,32];
}
and trying to access it from jscript like this
var TileArray=Tile_$$anonymous$$ap.map(34,34);
obviously i have no idea what i am doing or i wouldnt get errors
can someone please post the working code for this?
Like Statement pointed out (and I added it to the example), simply creating the array does not create the tile instances that you want inside the array. I will update the answer with a more detailed example.
i treid this and tried accessing from java like this Tile_$$anonymous$$ap.map(0,0).Tile_ID=7; and i get this error again i must be doing this wrong Assets/Scripts/tilemap.js(104,18): BCE0077: It is not possible to invoke an expression of type '(TileInfo, 2)'. using UnityEngine; using System.Collections; public class TileInfo { public int Tile_ID; public int Tile_$$anonymous$$od; } public class Tile_$$anonymous$$ap { public static TileInfo[,] map = new TileInfo[34,34]; void main() { for (int x=0; x<34; ++x) {
for (int y=0; y<34; ++y) {
map[x, y] = new TileInfo();
}}}}