- Home /
2-dimensional array in JS
Could anyone help me with 2d arrays?
Because I would like to store my item info loaded from an online database in a 2d array like:
//Item with ID #0
item[0,0] = "Chain Helmet"; //Name
item[0,1] = 10; //Sell price
item[0,2] = "ChainHelmet1"; //Prefab
//Item with ID #1
item[1,0] = "Plate Chest"; //Name
item[1,1] = 20; //Sell price
item[1,2] = "PlateChest1"; //Prefab
Would be nice if the array can hold floats/ints as well as strings (like above example)... I come from GameMaker Studio engine, so don't know if this is possible in Unity. The script reference about arrays is also hard to understand. Also don't know how to declare such an array... Hope you can help me with this one :D
Specifying C# or Javascript will help in getting an accurate answer.
Answer by Royall · Apr 17, 2014 at 05:33 PM
I think i fixed it myself. It looks like this is working:
class Item {
var name : String;
var prefab : String;
}
static var items : Item[];
function loadItems() {
items = new Item[2];
items[0] = new Item();
items[0].name = "Chain Helmet";
items[0].prefab = "ChainHelmet1";
items[1] = new Item();
items[1].name = "Plate Chest";
items[1].prefab = "PlateChest1";
Debug.Log(items[1].prefab);
}
Is this code correct? Or can it be shorter or something? Thx
Edit: Worked for me :D
There is nothing wrong with doing it this way, but you can put a constructor in your Item class and then declare the array statically:
#pragma strict
class Item {
function Item(n : String, p : String) {
name = n;
prefab = p;
}
var name : String;
var prefab : String;
}
private static var items : Item[]
= [Item("Chain Helmet", "ChainHelmet1"),
Item("Plate Chest", "PlateChest1"),
Item("Short $$anonymous$$nife", "Short$$anonymous$$nife1")
];
function Start() {
for (var item : Item in items) {
Debug.Log(item.name+", "+item.prefab);
}
}
Answer by Eric5h5 · Apr 17, 2014 at 04:36 PM
You do not want a 2D array, you want to use a custom class, and then have an array of that class.
class Item {
var name : String;
var price : int;
var prefab : String;
}
var items : Item[];
And how would you store and retrieve info with a class? :)
The same ways you would anything else. Look into serialization, or maybe X$$anonymous$$L, etc.
But I need items to be saved with an ID.. So how would I retrieve for example the price of item #5 (ID)
Ok I tried the following:
class Item {
var name : String;
var prefab : String;
}
static var items : Item[];
function loadItems() {
items[0].name = "Chain Helmet";
items[0].prefab = "ChainHelmet1";
items[1].name = "Plate Chest";
items[1].prefab = "PlateChest1";
Debug.Log(items[1].name);
}
But this doesn't seem to work... Trows me: NullReferenceException: Object reference not set to an instance of an object
I am probably doing it totally wrong... Any help? ^^