[System.Serializable]
public class Item()
{
string name;
ItemType itemType;
int itemId;
string itemDescription
}
public class TestClass : MonoBehaviour
{
// Defining a dictionary
private Dictionary<int, Item> itemDictionary = new Dictionary<int, Item>();
private void Start()
{
// Create new item
Item shield = new Item();
shield.name = "Shield";
shield.itemType = ItemType.Shield;
shield.itemId = 0;
shield.itemDescription = "Something to block attacks with";
// Add the first item to our dictionary
itemDictionary.Add(0, shield);
// Access the first item and display the name of the item in the console log
Debug.Log("First Item: " + itemDictionary[0].name);
}
}
Adding values to a dictionary is similar to a list but with one minor change, you have to provide a key with the value that you want to add. Accessing an value is also similar to a list but instead of using an index, you use the key associated with the value you want.
Looping Through A Dictionary
You can loop through a dictionary using a foreach loop, but there are three ways you can write that loop. The first being as a KeyValuePair, the second being just the keys and the third being just the values. Below are examples of all three loops.
[System.Serializable]
public class Item()
{
string name;
ItemType itemType;
int itemId;
string itemDescription
}
public class TestClass : MonoBehaviour
{
// Defining a dictionary
private Dictionary<int, Item> itemDictionary = new Dictionary<int, Item>();
private void Start()
{
// Create new item
Item shield = new Item();
shield.name = "Shield";
shield.itemType = ItemType.Shield;
shield.itemId = 0;
shield.itemDescription = "Something to block attacks with";
// Add the first item to our dictionary
itemDictionary.Add(0, shield);
// Create new item
Item sword = new Item();
sword.name = "Sword";
sword.itemType = ItemType.Sword;
sword.itemId = 1;
sword.itemDescription = "Something to attacks with";
// Add the second item to our dictionary
itemDictionary.Add(3, sword);
// Create new item
Item helmet = new Item();
helmet.name = "Helmet";
helmet.itemType = ItemType.Armour;
helmet.itemId = 2;
helmet.itemDescription = "Something to put on your head";
// Add the third item to our dictionary
itemDictionary.Add(6, helmet);
// Loop through dictionary using KeyValuePair
foreach(KeyValuePair<int, Item> entry in itemDictionary)
{
Debug.Log("Key: " + entry.key);
Debug.Log("Value: " + entry.value);
}
// Loop through dictionary using Key
foreach(int key in itemDictionary.keys)
{
Debug.Log("Key: " + key);
}
// Loop through dictionary using values
foreach(Item item in itemDictionary.values)
{
Debug.Log("Value: " + item.name);
}
}
}
Note that it is possible that all keys are not going to be sequential as demonstrated above. Also all keys should be unique, but there can be duplicate items. You can also check if a dictionary has a key by using the ContainsKey() function, this stops any exception errors due to missing keys.