- Home /
What am I doing wrong with hashtable.CopyTo?
I'm getting an error with the save routine for one of my javascript classes and I'm at a loss to see what's wrong with it.
public var RawSettings = new Hashtable();
// it gets loaded elsewhere with 3 key-value pairs, // verified by debug output showing a count of 3
function Save(){ Debug.Log("GamePrefs_Save initiated.\n Count is: " + RawSettings.Count ); var PrefKeys: String[]; if( FileName == "" ) { FileName = "Preferences"; Debug.Log("GamePrefs.Save: No FileName specified, using Preferences.ini"); } var srSaveFile : StreamWriter = new StreamWriter ( Application.persistentDataPath + "/" + FileName + ".ini" ); RawSettings.Keys.CopyTo(PrefKeys,0); for(var x = 0; x < PrefKeys.length; x++){ srSaveFile.WriteLine( PrefKeys[x] + "=" + RawSettings[PrefKeys[x]] as String ); } srSaveFile.Close (); Debug.Log( "GamePrefs: Saved " + FileName + " as " + Application.persistentDataPath + "/" + FileName + ".ini" ); }
Error message:
ArgumentNullException: Argument cannot be null. Parameter name: array System.Collections.Hashtable+HashKeys.CopyTo (System.Array array, Int32 arrayIndex)
Answer by loramaru · May 06, 2011 at 02:40 AM
You've only declared PrefKeys to be an array variable; you still need to instantiate an actual array object before making the call.
PrefKeys = new String[RawSettings.Keys.Count];
RawSettings.Keys.CopyTo(PrefKeys,0);
That was part of it. Now there's a new error with a String[] array or even an Array[] I get the same error. "InvalidCastException: Cannot cast from source type to destination type. System.Array.SetValue (System.Object value, Int32 index)"
Thanks for that tip though. :)
Oh and I upvoted your answer since it solves part of the problem, just hoping someone knows how to get it working in case another member needs to use the same function. I'm about ready to mirror the hashtable in an array at load so I can skip the CopyTo function altogether, though that's a kludgy fix. I just don't have time to rewrite the whole class and replace all the hashtable functions with array equivalents.
That sounds like you have a key in your hash table that isn't a string. Oh and Array[] wouldn't help as that would be an array or arrays. You could try Object[] which would be able to hold anything. However you probably should find where you are storing an unexpected value (non-String) in the hash table and adjust that.
Ah crap.. it was a typo in some copy-pasted lines that caused the second error. Your fix workes fully now. Thanks!
Your answer
Follow this Question
Related Questions
Hashtable and ArrayList problem 0 Answers
ExecutionEngineException: SIGILL 0 Answers
"Array out of range" when cycling weapons. 1 Answer
int array overflow exception 1 Answer
A null value was found where an object instance was required. 1 Answer