- Home /
How to use Javascript Array with classes?
Hi , I have checked the unity website for how to use the arrays but still am confused and get errors!
I'm trying to make a simple inventory and currently have a class called item.
class Item{
var damage : int;
var name : String;
var model : GameObject;
var icon : Texture;
}
However I don't know how to put this into a array , I am currently using the code below to just get the console to out the name of an item. I also seem to be getting different results depending on whether I select the "maximize on play" button in the editor.
var Inventory : Item[];
function Start () {
Inventory = new Item[10];
Inventory[1].damage = 1;
Inventory[1].name = "hello";
}
function Update () {
print(Inventory[1].name);
}
Any help on this topic , I will be extremely greatful for , Thanks =)
Answer by robertbu · Feb 12, 2014 at 02:10 PM
You not only have to create the array (i.e. new Item[10]), but you have to create each individual item that goes into the array. For example:
#pragma strict
class Item{
var damage : int;
var name : String;
var model : GameObject;
var icon : Texture;
}
var Inventory : Item[] = new Item[10];
function Start () {
Inventory[1] = new Item(); // <<========
Inventory[1].damage = 1;
Inventory[1].name = "hello";
Debug.Log(Inventory[1].name);
}
Note I've only create one item for entry index 1. Instead you might want to populate the entire list:
for (var i = 0; i < Inventory.Length; i++) {
Inventory[i] = new Item()
}
Hi , thanks for answering so quickly! I still have an issue though with getting values from the array , with the code below I keep getting this error "Array index is out of range".
function OnGUI(){
if(Input.Get$$anonymous$$ey("i")){
if(Inventory[0].name == "hello"){
//////GUI CODE IS HERE
}
}
}
As an educated guess. Either 1) make Inventory private:
private var Inventory : Item[] = new Item[10];
Or 2) move the 'Inventory = new Item[10]' back into Start().
Since your Inventory is public, it is taking its size from the Inspector rather than the initialization here. The initialization of public variables is only done at the time the script is attached, and it is likely that you already had the script attached when you made the changes.
I should point out that robertbu's original code, setting only Inventory[1], is rather misleading. Inventory[1] is actually the second element of the array (with Inventory[0] being the first). Arrays are zero indexed. I realise that, judging from your code above, you already know this, but I feel it's worth clearing up for others who might not.
yeh cheers did know already but thanks for the heads up :)