Key Not Found Exception?

Hi there. Opening a project recently, and received this error:

KeyNotFoundException: The given key was not present in the dictionary.
System.Collections.Generic.Dictionary`2[System.String,System.Boolean].get_Item (System.String key) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:150)

The error points towards this following piece of script:

public void Awake()
{
    if (soundDestroy)
        DontDestroyOnLoad(gameObject);
    else if (isCreated[gameObject.name])
        Destroy(gameObject);
    else
    {
        DontDestroyOnLoad(gameObject);
        isCreated[gameObject.name] = true;
    }
}

soundDestroy is a bool. The error seems to point specifically at that ‘else if’ line. Any ideas?

As the error suggests, the isCreated Dictionary does not contain a key that matches the gameObject’s name.

You could do a quick check beforehand:

  else if (isCreated.ContainsKey(gameObject.name) && isCreated[gameObject.name])

But that’s like putting a bandaid on the problem. You should dig in and see why the dictionary is missing that key, and if it’s intentional. Actually what script is that? Did you write it, or did it come with an asset?

The error says it all. You’re trying to get a value from a dictionary but the key does not exist.

A dictionary consists of key-value pairs.
The keys are treated like a set, they all have to be unique (that is, can only be contained once) and in your specific case, a boolean value is mapped to every key that is stored in the dictionary.

The ‘else if line’ tries to get the key named like the gameobject that this script is attached to (due to the use of gameObject.name) and the exception is thrown because there is no entry with this key in the dictionary.