I need to sort scores of players and thought of using associative arrays for this. I have a bit of a problem to get the code for this working in unity.
If I use this concept I get the error “type object does not allow slicing” when doing something like: print(_array[0][“a”]);
I also tried hashtables:
var newHash = new Hashtable();
newHash.Add("player"+1, 6);
newHash.Add("player"+2, 5);
for(key in newHash){
str = str + " - " + newHash[key];
}
print(str);
Adding values works fine but it prints " - System.Collection.DictionaryEntry -System.Collection.DictionaryEntry".
How do I sort a hashtable on the value? And then afterwards, how can I go through the hashtable and get the “players” out of the keys instead of getting “System.Collection.DictionaryEntry”?
Probably this can be done much easier but the the following works for the sorting part of the players depending on scores:
function SortHashtable (inpHash : Hashtable) {
var iVal; var key; var arrayValues = new Array(); var valuesKeysHash = new Hashtable(); var returnArray = new Array();
// create arrays of values and reverse keys and values in valuesKeysHash hashtable
for (key in inpHash.Keys) {
arrayValues[arrayValues.length] = inpHash[key];
valuesKeysHash.Add(inpHash[key], key);
}
// sort the array with values
arrayValues.Sort();
// create new array holding the new order of keys and return it
for (iVal in arrayValues)
returnArray[returnArray.length] = valuesKeysHash[iVal];
return returnArray;
}
There’s also a .Values property available from the Hashtable class (no need to iterate through with the keys to get the values). I guess I should have read your question more carefully
Yeh, I found that too. But, as it creates another hashtable where the key becomes the value and the value the key, I still need the key so I thought this was the easiest way to go.
Hashtable is a valid Unity type. It’s true, there’s no part of the docs that lists all the types. Also, another (less obvious) way of declaring a new hashtable is
function Start () {
var newHash = new Hashtable();
newHash.Add("player"+1, 6);
newHash.Add("player"+2, 5);
//don't forget to declare str or else you get an unknown identifier
//also make it a type String or else you get NullReference exception
var str:String;
for(key in newHash.Keys)
{
print(key+ " - " + newHash.Item[key]);
print(newHash[key]);
str = str + " - " + newHash[key];
}
print(str);
print(newHash["player1"]);
print(newHash.Count);
}