Other ways in tracing Error: System.ArgumentException: An element with the same key already exists in the dictionary. ?

Anyone had other ways in finding this type of error? It doesn’t point to anything if double-clicked, the project is large and it was written by a different programmer. So I can’t do any “remember where I wrote dictionaries” type of debugging. xD

If you could show me other methods to trace this that would be so awesome.

 Error: System.ArgumentException: An element with the same key already exists in the dictionary.
      at System.Collections.Generic.Dictionary`2[System.String,System.String].Add (System.String key, System.String value) [0x00000] in <filename unknown>:0 
      at us.UnityScriptCompilerFactory.FromCommandLineOptions (us.CommandLineOptions options) [0x00000] in <filename unknown>:0 
      at us.UsModule.compile (us.CommandLineOptions options) [0x00000] in <filename unknown>:0 
      at us.UsModule.runWithCommandLine (System.String[] commandLine) [0x00000] in <filename unknown>:0 
      at us.UsModule.Main (System.String[] argv) [0x00000] in <filename unknown>:0

Hi @k3ndro, these kinds of errors are usually pretty easy to track down because how many dictionaries are you using? That said, it may be harder to find the root cause of the logic of why your code is adding a duplicate - it just depends on where you are using the dictionary (e.g. when your Add is inside some recursive function it can be very difficult to find the underlying cause).

Put a debug.log wherever you have a dictionary.Add call, before the call, and list the key you are trying to add. If you add to the dictionary in more than one place, preface the log with the name of the function you are in.

For example:

 Debug.Log( "Start() line 12 Add Key = "  + your_Key_Variable );
           // and in another function:
 Debug.Log( "SpawnEnemies() line 37 Add Key = "  + any_other_Key_Variable );
           // and so on....

The last key you see in the log before the error is the duplicate, and you will find it previously in the log. Then your fun begins, because the problem is with the code logic.