The context: Dictionary<Enum, List<Class>> abc = new Dictionary<Enum, List<Class>>();
The attempt: abc[enumVar].Add(classVar);
The error: The given key was not present in the dictionary.
Isn’t the point of [ ]
to create the key if it doesn’t exist?
Edit: The Dictionary is initialized literally above I start iterating. Code highlight confirms it. Both enumVar and classVar are a thing, I tested it with Debug.Log.
You need to use TryGetValue from the dictionary, and add a new list to the dictionary if one doesn’t exist yet.
I actually made an extension function for this situation which I use in all my projects: unity-extensions/Runtime/Extensions/CollectionExtensions.cs at 39ed64365dddde764b4baeb5968eb6e1523d2bde · jschiff/unity-extensions · GitHub
Then using this extension you can do this:
var myList = abd.ComputeIfAbsent(classVar, () => new List<Class>());
myList.Add(myNewElement);
I modeled this from the ComputeIfAbsent method for Maps in Java: Map (Java Platform SE 8 )