- Home /
Generic dictionary emptying itself?
Anyone know why a custom dictionary, generated and populated in code, would work fine for a while and then spontaneously lose all its entries?
I'm making a card game, often need to move an object relating to a card suit, and rather than searching for the object by name (which worked fine) I thought a dictionary would be more elegant... and it works perfectly for a while, then seemingly after a few minutes of gameplay, starts throwing up KeyNotFoundException: The given key was not present in the dictionary.
Trimmed down code as follows: (JS/US)
#pragma strict
import System.Collections.Generic;
var plates = new Dictionary.<String,Transform>();
var pct:Transform;
var pdt:Transform;
var pht:Transform;
var pst:Transform;
//the transforms are allocated manually in the editor
function Start () {
plates.Add("club",pct);
plates.Add("diam",pdt);
plates.Add("hear",pht);
plates.Add("spad",pst);
}
Then later, I'll want to move the "pct" object using something like:
function selectcard(){
...
var suit="club";
plates[suit].position=Vector3(0,1.6,-1);
...
}
Apologies for not posting full code, it's over 1000 lines dealing with other objects and events.
As I said earlier, it all works fine for a while then starts throwing up errors. Outside of Start() the dictionary is only ever referenced to change the transform's position, nothing added to or deleted from it.
I'm certain the dictionary is being emptied as I've checked using
print(plates["club"]); //and likewise for "diam", "hear", "spad"
print(plates.Count);
...all of which return the expected results until the error appears.
Are there any methods not directly related to dictionaries, which might be doing this as a side effect? I'm at a loss, may have to go back to GameObject.Find every time I move these items :/
After much further testing, this might be happening when I make and save changes in $$anonymous$$onoDevelop during preview play; so hopefully won't affect the final build, but it would be nice to get more certainty about what is going on
Well, Dictionaries can't be serialized so you might have to convert it to a custom class or two lists, one containing keys and one containing values and save those ins$$anonymous$$d, and repopulate it with the two deserialized lists after loading (assu$$anonymous$$g you use serialization).
Your answer
Follow this Question
Related Questions
Setting Scroll View Width GUILayout 1 Answer
I have been watching his tutorial but nothing happens 0 Answers
For statement errors? 1 Answer
BCE0049 error with network script 0 Answers