Hi everyone!
In my current project, I’m keeping track of all existing objects with some public static Dictionaries. When the user creates a new object, I add the new GameObject to one Dictionary, the instance of the corresponding class in an other Dictionary and a reference between those two in a third Dictionary.
public class EnvironmentData
{
[...] // some irrelevant references
private static Dictionary<int, Item> items = new Dictionary<int, Item> ();
private static Dictionary<Item, int> itemsReverse = new Dictionary<Item, int> ();
private static Dictionary<int, GameObject> gameObjects = new Dictionary<int, GameObject> ();
// ===================================
public static void AddItem (int objID, Item item)
{
items.Add (objID, item);
itemsReverse.Add (item, objID);
}
public static void AddGameObject (int objID, GameObject gameObject)
{
gameObjects.Add (objID, gameObject);
}
// ===================================
public static Item GetItem (int id)
{
Item item;
items.TryGetValue (id, out item);
return item;
}
public static int GetID (Item item)
{
int id;
itemsReverse.TryGetValue (item, out id);
return id;
}
public static GameObject GetGameObject (int id)
{
GameObject go;
gameObjects.TryGetValue (id, out go);
return go;
}
// ===================================
public static void ClearItems ()
{
items.Clear ();
itemsReverse.Clear ();
}
public static void ClearGameObjects ()
{
foreach (GameObject go in gameObjects.Values) {
GameObject.Destroy (go);
}
gameObjects.Clear ();
}
}
Now, when I do this during normal runtime, there’s no problem at all. Everything is working perfectly fine. However, I also offer the possibility to save and load those setups. And for the most part even that works. But I have 1 Items whose instances are recognized as identical by Unity and even share the same HashCode, after loading them. Again: This only happens after clearing everything and loading those instances, not when manually creating them at runtime.
So, when trying to load such a setup Unity gives me this Error message:
ArgumentException: An element with the same key already exists in the dictionary.
System.Collections.Generic.Dictionary`2[Item,System.Int32].Add (.Item key, Int32 value) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:404)
EnvironmentData.AddItem (Int32 objID, .Item item) (at Assets/Scripts/StaticScripts/EnvironmentData.cs:20)
which corresponds with line 12 ( itemsReverse.Add (item, objID); ) in this snippet.
I know which Item is affected, but I don’t know why. It’s declared the exact same way as all the other Items, so I’m kinda lost here.
Cheers