- Home /
How to add class to a static Generic List
for writing an simple advanture inventory, I'm going to learn Generic List But, it made me crazy :( How I can add class to this static list?
#pragma strict
import System.Collections.Generic;
static var item = new List.<itemClass>();
class itemClass
{
var itemName : String;
var itemIcon : Texture;
var itemDescription : String;
}
item.Add(........);
Answer by fafase · Jan 23, 2014 at 08:34 AM
You need an instance of the class to be able to add it:
static var item = new List.<itemClass>();
function Start()
{
var itemToAdd :itemClass = new itemClass();
item.Add(itemToAdd);
}
But make sure a static list is what you need. In your case, your list is static but your object are not. So when loading a new scene, those objects are referred in the list and won't be destroyed. In the end, if you store 100 items and you don't need them anymore make sure to clear your list.
ok, tnx... but another question: how can I use GameObject Name ins$$anonymous$$d of "itemToAdd"? Because I'm adding Class information from another object var itemToAdd :itemClass = new itemClass();
I don't really see what you mean but I think you are trying to run before crawling. I guess you are just starting and all this is quite confusing. It will just get more confusing if you do not learn program$$anonymous$$g basics. I would recommend to start there.
You can only add references of the type that the list is declared for.
Here you declare the list for itemClass. So you the whole reference. If you are after a collection where you can use the name of the item then you want to look into Dictionary where you can couple the item name and the item itself.
Your answer
Follow this Question
Related Questions
how to add game object to custom class with for loop 2 Answers
Errors when trying to construct custom class in UnityScript 1 Answer
list.Add() not working 3 Answers
How to treat Input.GetAxis as Input.GetButtonDown? 9 Answers
Fade in Fade out in unity 1 Answer