I'm using Unity Engine with C#.
Currently, I have a weird issue. Here's the code for my dictionary:
private Dictionary<int, List<IExplosionDamageGiver>> m_DeployedExplosiveMap = new Dictionary<int, List<IExplosionDamageGiver>>();
The key is a unique ID(using Photon's ViewID) and the value is a list of IExplosionDamageGiver objects.
Here's the code for adding the actual value into the dictionary:
print("Deployer: " + deployerViewID);
print("Contains Deployer: " + m_DeployedExplosiveMap.ContainsKey(deployerViewID));
if (m_DeployedExplosiveMap.ContainsKey(deployerViewID) == false) {
print("Create List for " + deployerViewID);
m_DeployedExplosiveMap.Add(deployerViewID, new List<IExplosionDamageGiver>());
print("Current Keys: " + m_DeployedExplosiveMap.Keys.Count);
foreach (var item in m_DeployedExplosiveMap) {
print("Key: " + item.Key + ", Count: " + item.Value.Count);
}
}
else {
print("List for " + deployerViewID + " is already exists");
}
m_DeployedExplosiveMap[deployerViewID].Add(damageGiver);
print("Deployed Count: " + m_DeployedExplosiveMap[deployerViewID].Count);
If there's no key in the dictionary, create a new key-value pair then use [] to update the value. Value is a list and used List.Add add new item to the list.
Here's the logs trying deployerViewID 2001:
Deployer: 2001
Contains Deployer: False
Create List for 2001
Current Keys: 1
Key: 2001, Count: 0
Deployed Count: 1
Running the same logic with the same deployerViewID 2001 works fine. Dictionary has 1 key, and the value List is keep adding a new element.
However, when the same logic with a different deployerViewID 1003 causes weird results. I expected that the key 1003 didn't exist in the dictionary so created a new key-value pair, and put the object in the just-created List for ID 1003, but it wasn't. Instead, it ERASES the key-value for deployerViewID 2001. It's just gone.
Deployer: 1003
Contains Deployer: False
Create List for 1003 // -> Works as expected. New int, List pair created.
Current Keys: 1 // WTF? Why dictionary have 1 key? It is supposed to be 2 keys!!
Key: 1003, Count: 0
Deployed Count: 1
I used foreach to iterate the dictionary but key 2001 and its value are just gone. Is this how the Dictionary works in C#? I used this method with many different game scripts but none of them had this issue. Only this code has trouble.
Seriously there's no extra code that accesses the dictionary. That's all the code. Is this a glitch or is my knowledge is wrong? Can anyone please explain to me what the heck is going on?