Quick answer: dictionary[key] throws KeyNotFoundException when the key is not in the dictionary. Read with TryGetValue and handle the missing case, then find out why the key is missing: the dictionary was not filled yet, Unity never serialized it, the id came from an old save, the string differs by case or whitespace, or the key type compares by reference.

A shop opens, an item id goes into a dictionary lookup, and the Console prints a KeyNotFoundException. Swapping the indexer for TryGetValue stops the exception, but the more useful question is why a key you expected to be there is absent. In Unity that usually traces back to data: ids stored in a save file or JSON, a lookup that runs before the dictionary is built, or a Dictionary field the engine silently refuses to serialize. This guide goes through the causes in the order you are likely to meet them, shows how to tell them apart from the Console, and gives code for each fix.

The exact error

Unity 2022 LTS and Unity 6 include the key in the message:

KeyNotFoundException: The given key 'sword_03' was not present in the dictionary.
System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) (at <...>:0)
Shop.GetPrice (System.String itemId) (at Assets/Scripts/Shop.cs:27)

Older Unity versions, with the older Mono class libraries, print it without the key:

KeyNotFoundException: The given key was not present in the dictionary.

The frame Dictionary`2.get_Item is the indexer, the square-bracket read. The line under it is your code. Where this page shows <...>, Unity prints a long hex id that identifies the library and can be ignored. Being an ordinary .NET exception, it fires the same way in the editor, in Mono builds and in IL2CPP builds on every platform.

Which calls throw and which do not

CallKey missing
value = dict[key]Throws KeyNotFoundException
dict[key] += 1Throws: it reads before it writes
dict[key].Add(x)Throws: the read comes first
dict[key] = valueAdds the key, never throws
dict.TryGetValue(key, out v)Returns false, v is the default
dict.ContainsKey(key)Returns false
dict.Remove(key)Returns false

The second and third rows catch people out. A counter written as counts[itemId] += 1 throws the first time each item is picked up.

What causes it

  1. An id from a save file or JSON that the game no longer knows. The save says the player owns "sword_03"; you renamed it to "iron_sword" two patches ago. Enums have the same problem: JsonUtility stores an enum as its number, so removing or reordering members makes an old save’s 7 point at a different member or at none.
  2. The lookup runs before the dictionary is filled. ItemDatabase builds its dictionary in Start, and another script’s Awake or Start asks for an item first. It often works in one scene and fails in another, because execution order between scripts is not guaranteed.
  3. Unity did not serialize the dictionary. A Dictionary field is not saved, with or without [SerializeField], and never shows in the Inspector. Entries added by an editor script, OnValidate or a context menu exist only until the next domain reload. They are not stored in the scene or prefab, so a build starts with an empty dictionary. The same happens when scripts recompile during Play mode: the field resets and Awake does not run again.
  4. The string is almost the same. "Sword" against "sword", a trailing space typed into the Inspector, or a \r left on the last column of a CSV saved with Windows line endings.
  5. The key type compares by reference. A class used as a key without Equals and GetHashCode only matches the same instance. new GridCell(2, 5) never finds an entry added with a different new GridCell(2, 5). A Vector3 key has a related problem: its Equals is exact, so two positions that differ in the last float bit are different keys.
  6. The key changed after it was added. If GetHashCode depends on a mutable field and you change that field, the entry sits in the wrong bucket and can no longer be found, even with the same object.
  7. A GameObject, Collider or component key from another lifetime. After a scene reload the “same” enemy is a new object, and a static dictionary filled in the old scene does not contain it. The reverse also happens: OnDisable removed the entry, and a late OnTriggerExit, coroutine or animation event still asks for it.

Causes 1 to 4 account for most reports. The last three are rarer and tend to show up in grid, pathfinding and registry code.

How to find which cause is yours

Double-click the Console entry to open the line. Then log three things just before the lookup:

Debug.Log($"key=[{itemId}] length={itemId.Length} count={prices.Count}", this);
Debug.Log("keys: " + string.Join(", ", prices.Keys), this);

The brackets around the key in the first log line are there so a leading or trailing space is visible.

Fix 1: read with TryGetValue and say what was missing

// Broken
int price = prices[itemId];

// Fixed
if (!prices.TryGetValue(itemId, out int price))
{
    Debug.LogError($"Shop: no price for item '{itemId}' ({prices.Count} items loaded)", this);
    return;
}

The log line matters as much as the guard. “No price for item ‘sword_03’, 0 items loaded” tells you the cause from a player’s log without a debugger. For the write-side cases:

// Counter: works whether or not the key exists
counts.TryGetValue(itemId, out int owned);   // owned is 0 when missing
counts[itemId] = owned + 1;

// List per key: create the list on first use
if (!enemiesByType.TryGetValue(type, out List<Enemy> list))
{
    list = new List<Enemy>();
    enemiesByType[type] = list;
}
list.Add(enemy);

Use ContainsKey when you only need a yes or no. if (dict.ContainsKey(k)) v = dict[k]; works but looks the key up twice, and TryGetValue does it once. Where a fallback is correct (a missing volume setting means 1.0), a small helper keeps call sites short:

public static class DictionaryExtensions
{
    public static TValue GetOrDefault<TKey, TValue>(
        this Dictionary<TKey, TValue> dict, TKey key, TValue fallback = default)
    {
        return dict.TryGetValue(key, out TValue value) ? value : fallback;
    }
}

With the default .NET Standard 2.1 API level, the built-in GetValueOrDefault does the same. Do not use a fallback where a missing key is a bug: a missing price that quietly becomes 0 gives players free items.

Fix 2: validate ids when data is loaded

Check saved ids once, at load, instead of trusting them at every lookup later:

foreach (string id in save.inventoryIds)
{
    if (itemsById.TryGetValue(id, out ItemDef def))
        inventory.Add(def);
    else if (renamedIds.TryGetValue(id, out string newId) && itemsById.TryGetValue(newId, out def))
        inventory.Add(def);
    else
        Debug.LogWarning($"Save v{save.version}: unknown item id '{id}' dropped");
}

Keep a renamedIds map for every id you ever change, and never reuse an old id for a new item. For enums that reach disk, give members explicit numbers, never renumber them, and reject undefined values with Enum.IsDefined(typeof(ItemType), value) before using one as a key.

Fix 3: fill the dictionary before anyone reads it

Build lookup tables in Awake and read them from Start or later. For objects that are active when a scene loads, Unity calls every Awake before any Start. When readers also run in Awake, build on first use instead:

private Dictionary<string, ItemDef> itemsById;

public bool TryGetItem(string id, out ItemDef def)
{
    if (itemsById == null) BuildLookup();
    return itemsById.TryGetValue(id, out def);
}

Fix 4: serialize a list, build the dictionary at runtime

// Broken: Unity ignores this field. It is empty in a build.
public Dictionary<string, AudioClip> clips = new Dictionary<string, AudioClip>();

Serialize a list of pairs, which the Inspector can show, and turn it into a dictionary in Awake:

[System.Serializable]
public struct NamedClip
{
    public string id;
    public AudioClip clip;
}

public class SoundBank : MonoBehaviour
{
    [SerializeField] private List<NamedClip> entries = new List<NamedClip>();
    private Dictionary<string, AudioClip> clips;

    void Awake()
    {
        clips = new Dictionary<string, AudioClip>(
            entries.Count, System.StringComparer.OrdinalIgnoreCase);

        foreach (NamedClip entry in entries)
        {
            string id = entry.id == null ? "" : entry.id.Trim();
            if (id.Length == 0 || !clips.TryAdd(id, entry.clip))
                Debug.LogWarning($"SoundBank: empty or duplicate id '{entry.id}'", this);
        }
    }
}

This fixes cause 4 at the same time: StringComparer.OrdinalIgnoreCase makes "Sword" and "sword" the same key, and Trim() removes stray spaces and line endings. Trim the key at lookup too if it comes from a file. TryAdd is available with the default .NET Standard 2.1 API level in 2022 LTS and Unity 6. If the dictionary must survive script recompiles in Play mode, implement ISerializationCallbackReceiver and rebuild it in OnAfterDeserialize instead of Awake.

Fix 5: give keys value equality and keep them immutable

// Broken: a class key compares by reference
public class GridCell { public int x, y; }

// Fixed: a readonly struct with explicit equality
public readonly struct GridCell : System.IEquatable<GridCell>
{
    public readonly int x, y;
    public GridCell(int x, int y) { this.x = x; this.y = y; }
    public bool Equals(GridCell other) => x == other.x && y == other.y;
    public override bool Equals(object obj) => obj is GridCell other && Equals(other);
    public override int GetHashCode() => (x * 397) ^ y;
}

For grid coordinates, Vector2Int and Vector3Int already do this. Convert world positions with Vector3Int.RoundToInt(position) or Grid.WorldToCell and do not use raw Vector3 keys. For dictionaries keyed by scene objects, remove the entry in OnDisable, read with TryGetValue in callbacks that can arrive late, and clear static dictionaries when a scene unloads.

How to confirm the fix

Test the paths the editor hides. Make a build and run it, since an unserialized dictionary only shows there. Load a save from an older version of the game (keep a folder of them for this). Edit a script while in Play mode and trigger the lookup again. For string ids, try one with different case and one with a trailing space in the data file. The pass condition is no KeyNotFoundException in Player.log, and a warning that names the id for every bad entry you planted.

Getting the key from players’ machines

The Bugnet Unity SDK files unhandled exceptions and Debug.LogError calls as reports, with the stack trace, recent log lines, game version, platform and OS. On current Unity versions the exception message already contains the key, and reports with the same title stack, so 'sword_03' becomes one entry with an occurrence count instead of a pile of duplicates. On older versions every missing key has the same message and lands in one entry, which is a reason to log the key yourself as in Fix 1. Bugnet does not read the player’s save file. If the save version or the source of the id matters, put it in the log message. Reports also accept text and JSON attachments up to 10 MB, which is enough room for most save files.

Frequently asked questions

What does KeyNotFoundException mean in Unity?

Code read a dictionary with square brackets using a key the dictionary does not contain. It is a standard .NET exception, not a Unity one. Reading with TryGetValue avoids the throw, and logging the missing key shows whether the data or the load order is at fault.

Should I use ContainsKey or TryGetValue?

Use TryGetValue when you need the value, because it checks and fetches in a single lookup. ContainsKey followed by the indexer does the lookup twice. ContainsKey is the right call when you only need to know whether the key exists.

Why is my Dictionary empty in the build but full in the editor?

Unity does not serialize Dictionary fields, so entries added in the editor by a script or custom inspector are never saved into the scene or prefab. Serialize a list of key and value pairs and build the dictionary from it in Awake.

Why does the error not show which key was missing?

Older Unity versions use class libraries whose message has no key in it. Unity 2022 LTS and Unity 6 print the key in quotes. On any version you can use TryGetValue and log the key, the dictionary count and where the key came from.

How do I make dictionary string keys case-insensitive?

Pass a comparer when you create the dictionary: new Dictionary of string keys with StringComparer.OrdinalIgnoreCase as the constructor argument. Lookups then ignore case. Trim the key as well if it comes from a file or an Inspector field, since whitespace still counts.

TryGetValue stops the exception, but the missing key is still a fact about your data. Log the key and the dictionary count where it fails, so the next report tells you which of the two was wrong.