So I’ve used dictionaries, but there’s 1 thing that makes them difficult (for me) to use in scripts. That’s that they need to be declared in every function. For example, this won’t work:
public Dictionary<string, int> InventoryItems;
// Use this for initialization
void Start ()
{
InventoryItems.Add("Test", 1);
}
Instead, I need to do this:
// Use this for initialization
void Start ()
{
Dictionary<string, int> InventoryItems = new Dictionary<string, int>();
InventoryItems.Add("Test", 1);
}
However, when constantly getting values from a dictionary from different functions, it becomes very difficult to work with as each function has its own dictionary (this also adds excess garbage allocation, and from what I’ve heard, it’s best to avoid relying on the GC). I could save the dictionary via serialization and access it from multiple functions that way, but that’s much slower and makes things more complicated than they should be.
Since I haven’t found a workaround for that issue, I’ve lately been using 2 Lists instead.
List<string> InventoryNames;
List<int> InventoryItems;
// Use this for initialization
void Start ()
{
InventoryNames.Add("Test");
InventoryItems.Add(1);
}
Is this bad practice, and if so, why should I avoid it?
I’m not sure if its bad but it could be hard to maintain.
I would just make a struct that holds a string and an int.
struct InventoryItems
{
public InventoryItems(string item, int numItems)
{
name = item;
items = numItems;
}
public string name;
public int items;
}
List<InventoryItems> items;
void Start()
{
items.Add (new InventoryItems("Test", 1));
}
The problem with maintaining multiple list to represent a single value is that you have to maintain those list. Get one list out of sync and suddenly all your data is not lining up. Even if you did have issues with dictionaries, you’d be better have making a class that has the values you want and then creating a list of that instead. However, in this case, @Kiwasi has the right answer unless you are trying to do.
To note, list require initialization also, but when public, the inspector will handle that for you which is why you may not notice that. Dictionaries, by default, aren’t handle in the inspector.