- Home /
Modifying scene objects programatically references prefab
Hi,
I have a scene where I create gameobjects from a prefab in the Resources folder at runtime:
var runtimeObject =(GameObject)UnityEngine.GameObject.Instantiate(Resources.Load(actorsTemplate_[rr]));
These object have a dictionary member called private
private Dictionary<string, float> floatUpdate;
At runtime, I add some stuff to the dictionaries in this way:
public void SetFloatParameter(string Name, float value)
{
if (floatUpdate.ContainsKey("Name"))
floatUpdate[Name] = value; // !!LINE #1
else
floatUpdate.Add(Name, value); // !!LINE #2
}
The problem I'm facing is:
ArgumentException: An element with the same key already exists in the dictionary.
on the !!LINE #1 (as specified in the code block after // comment).
What could be causing this?
Thanks.
Are you absolutely sure it's the line you're specifying? Because the indexer (the []) should not be able to throw a ArgumentException - only the Add method does that. Check the docs here.
Furthermore, doing this in an empty scene:
void Start() {
Dictionary<string, int> dict = new Dictionary<string, int>();
dict["foo"] = 0;
Debug.Log(dict["foo"]);
dict["foo"] = 1;
Debug.Log(dict["foo"]);
}
Prints 0 and then 1 as expected, with no errors.
The issue was that I used if (floatUpdate.Contains$$anonymous$$ey("Name")) ins$$anonymous$$d of if (floatUpdate.Contains$$anonymous$$ey(Name)).
Answer by BMayne · Dec 16, 2014 at 01:41 PM
Hey there,
Your issue is the contains key check you are doing. You check to see if "Name" is a key. This will never be true unless you sent "Name" in with that function. Change "Name" to Name and you will be fine.
public void SetFloatParameter(string Name, float value)
{
if (floatUpdate.ContainsKey(Name))
floatUpdate[Name] = value; // !!LINE #1
else
floatUpdate.Add(Name, value); // !!LINE #2
}