Dictionaries — Unity C#

Imran Momin
3 min readApr 18, 2021

--

The Dictionary type steps away from arrays and lists by storing value pairs in each element, instead of single values. These elements are referred to as key-value pairs: the key acts as the index, or lookup value, for its corresponding value. Unlike arrays and lists, dictionaries are unordered. However, they can be stored and ordered in various configurations after they are created.

Basic Syntax

Declaring a dictionary is almost the same as declaring a list, but with one added detail — both the key and the value type need to be specified inside the arrow symbols:

Dictionary<keyType, valueType> name = new Dictionary<keyType, valueType>();

To initialize a dictionary with key-value pairs:

· Use a pair of curly brackets at the end of the declaration.

· Add each element within its pair of curly brackets, with the key and the value separated by a comma.

· Separate elements with a comma, except the last element where the comma is optional.

Dictionary<keyType, valueType> name = new Dictionary<keyType, valueType>()
{
{key1, value1},
{key2, value2}
};

An important note to consider when picking key values is that each key must be unique, and cannot be changed. If you need to update a key, change its value in the variable declaration or remove the entire key-value pair and add another in code.

Setting up an inventory — Example

Let’s create a dictionary to store items that a character might carry:

  1. Declare a dictionary with a key type of string and a value type of int, called itemInventory.
  2. Initialize it to new Dictionary<string, int>(), and add three key-value pairs. Make sure each element is in its pair of curly brackets.
  3. Add a debug log to print out the itemInventory.Count property so that we can see how items are stored.
  4. Save the file and hit Play.

Working with dictionary pairs

Key-value pairs can be added, removed, and accessed from dictionaries using both subscript and class methods. To retrieve an element’s value, use the subscript operator with the element’s key — in the following example, numberOfPotions would be assigned a value of 5.

int numberOfPotions = itemInventory["Potion"];

An element’s value can be updated using the same method — the value associated with “Potion” would now be 10:

itemInventory["Potion"] = 10;

Elements can be added to dictionaries in two ways: with the Add method and with the subscript operator. The Add method takes in a key and a value and creates a new key-value element, as long as their types correspond to the dictionary declaration:

itmeInventory.Add("Throwing Knife", 3);

If the subscript order is used to assign a value to a key that doesn’t exist in a dictionary, the compiler will automatically add it as a new key-value pair. For example, if we wanted to add a new element for “Bandage”, we could do so with the following code:

itmeInventory["Bandage"] = 5;

This brings up a crucial point about referencing key-value pairs: it is better to be certain that an element exists before trying to access it, to avoid mistakenly adding new key-value pairs. Pairing the ContainsKey method with an if statement is the simple solution since ContainsKey returns a Boolean value based on whether the key exists. In the following example, we are sure that the “Aspirin” key exists before modifying its value:

if(itemInventory.ContainsKey{"Aspirin"))
{
itemInventory["Aspirin"] = 3;
}

Finally, a key-value pair can be deleted from a dictionary using the Remove method, which takes in a key parameter:

itmeInventory.Remove("Antidote");

Dictionaries offer a variety of methods and functionality to make development easier.

--

--

Imran Momin
Imran Momin

Written by Imran Momin

A VR/AR developer, who enjoys making games and developing interactive environments using Unity’s XR integration toolkit for Oculus quest and HTC vive devices.

Responses (2)