Dictionary- C# Skill in Unity: 8
Objective: knowing the basic usage of Dictionary in Unity.
In Unity, there is another function can be used to store data, that is Dictionary. Unlike List is easy to create, Dictionary requires 2 data type to create: Key & Value. That makes Dictionary would be used to search a data/value with matched key.
The declaration of a new Dictionary is quite similar to List. Except you need 2 data type to declare a new Dictionary.
The key would be a unique data to locate the value. As the item data we had used in the previous article, an item has a name(string) and an ID(integer). We can use ID as the key of this Dictionary; and the value would be class Item.
To add a new item to Dictionary, let’s create some items first.
To demonstrate data locating in Dictionary later, I would not input the data info of shirt.
With these 2 items declaration, we can add them into Dictionary by using Dictionary.Add(key, value).
Because we use integer as the key, we can simply use the ID of Item.
And we can also hard code the integer as key to add another item.
Now we have added 2 items to itemDictionary. Since Dictionary can not reveal in editor like List does, we can only access it in script.
List out contents of Dictionary
Let’s try to list out all contents in our Dictionary. To do this, we can use “foreach” loop to extract all specific type of data.
Since there are 2 type within 1 data, we can use KeyValuePair as locating type.
Here is the result of it.
Locate specific item
The speciality of Dictionary is you can locate the value with key. We can use Dictionary.ContainKey(key) as condition to locate it.
You should get the right value if you input the right key.
We can also use integer to Dictionary.ContainKey(key).
And of course, if you input the key that does not exist, it would return nothing as result.
Besides locate an item with key, you can also locate an item with value by using Dictionary.ContainValue(value).
As looking for a specific data, Dictionary would be handy to deal with a huge database. This is really helpful to create a RPG game.