Last Updated on 2021-11-02 by Clay
In Unity/C#, it is quite convenient to use Dictionary to store data, because the storage method of the dictionary is key-value correspondence, a key corresponds to a single value.
For example, it is easy to associate the item number with the item name.
The following record how to initialize a Dictionary data type variable, and add the data, get the data.
Dictionary Operation
Dictionary<TKey,TValue> Class
- Namespace: System.Collections.Generic
- Assembly: mscorlib.dll, System.Collections.dll
Initialization
Remember do not just use Dictionary<int, string> dict;
to initialize, otherwise you will find that you cannot add any objects later.
Dictionary<int, string> dict = new Dictionary<int, string>();
Add the data
dict.Add(0, "bottle");
dict.Add(1, "letter");
dict.Add(2, "candy");
Get the data
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(0, "bottle");
dict.Add(1, "letter");
dict.Add(2, "candy");
Console.WriteLine(0);
Console.WriteLine(dict[0]);
Ouptut:
0
bottle
Get the number of data
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(0, "bottle");
dict.Add(1, "letter");
dict.Add(2, "candy");
Console.WriteLine(dict.Count);
Output:
3
Clear
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(0, "bottle");
dict.Add(1, "letter");
dict.Add(2, "candy");
dict.Clear();
Console.WriteLine(dict.Count);
Output:
0
References
- https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-5.0
- https://learn.unity.com/tutorial/lists-and-dictionaries