- Home /
for (var x in object) giving x = System.Collections.DictionaryEntry
So i have an object called listOfStuff, to which i add variables through
function storeNew(item,value){
listOfStuff[item] = value;
}
then i have a loop function:
function listData(){
for(var x in listOfStuff){
Debug.Log(x + "is worth" + listOfStuff[x]);
}
}
which should write all the data added to the object, so
storeNew("banana",2);
storeNew("diamond",1000);
showData;
//should result in:
//"banana is worth 2"
//"diamond is worth 1000"
this only logs System.Collections.DictionaryEntry, why is that?
so you call storeNew as:
storeNew("banana",2);
aka
listOfStuff["banana"] = 2;
"banana" tends not to be a standard index number...
and then say listOfStuff = new SomeClass[] then listOfStuff is an array of 'SomeClass' elements. Then your for loop is doing:
for(var x in listOfStuff){
// x is of type 'SomeClass' at this point
// listOfStuff[x] is trying to do listOfStuff['SomeClass' instance] when it expects an integer index value
Debug.Log(x + "is worth" + listOfStuff[x]);
}
but listofstuff is not an array, but an object. It's created with var listOfstuff = {};
Also i tried entering a debug.log(listOfStuff[item]) into storeNew, and it properly logged the value as i wanted it to.
It seems to be just in the loop that it can't access it
Answer by Scribe · Jan 12, 2015 at 09:07 AM
Okay so I don't really use unityscript any more and hadn't realized the meaning of the syntax but on a second look (and from the name of the error!) I'm guessing it is the unityscript equivalent of a C# dictionary so ~hopefully~ the following might work:
var listOfstuff = {};
function Start () {
listOfstuff["test"] = 1;
listOfstuff["test2"] = 2;
for(var entry in listOfstuff){
Debug.Log(String.Format("{0} is worth {1}", entry.Key, entry.Value));
}
}
so basically the important part is that to get teh first part you use entry.Key and the second part entry.Value!
Hope that helps, sorry for my rather sarky comment, I was definitely in the wrong :)
Scribe