- Home /
ArrayList Problem. How to access using index.
Ok, so I'm having an issue with ArrayList. I seem to be unable to access the arraylist using an index. Look at the following example: (ps, Core.Score is a struct)
ArrayList HighScoreList = new ArrayList(); Core.Score tmpScore = new Core.Score(); tmpScore.Name = "ABRAKADABRA"; tmpScore.HighScore = 33234; tmpScore.yOffset = 0.3f; HighScoreList.Add(tmpScore);
So, if I now access this Highscorelist using a foreach loop, like so: foreach(Core.Score score in HighScoreList) { highscoreName.guiText.text = score.Name; } This works fine, I get ABRAKADABRA printed nicely.
However, using a simple index does not work at all.. I would have though i should be able to write: highscoreName.guiText.text = HighScoreList[0].Name;
But, it doesn't find the struct in index 0. I get this error: "Object" does not contain a definition for "Name".
So, what's going on here? Some hint would be fantastic :)
Thanks.
Kjetil
Answer by map-solar · Jul 17, 2010 at 02:59 PM
ArrayList contains all items as objects (that's where the error messages comes from - indeed, that Object does not contain a definition), so you have to cast them back to your struct.
highscoreName.guiText.text = ((Core.Score)HighScoreList[0]).Name;
The other option is to just use generics: List<T>
from System.Collections.Generic
for using List - it'll help with readability, and skips having to box and unbox the struct when getting or setting in the list
Well, I tried something like that, and it gives me the same error. It's something about the struct. If I add a simple string in the highscore list, and access the index directly and using a string cast, then it works. But the example above does not. :/ I tried with a normal array, and that works fine, but I wanted to use the built in sorting method within ArrayList.
System.collections.generic does not seem to work for unity iphone.
btw, related to the comment above, do I need to add some new references perhaps? currently I have the unity dll's + system, system.core and system.xml
You need to change to a different compile profile (higher .NET version) to make it work. but I just noticed a problem with the code in the answer above. It should be ((Core.Score)HighScoreList[0]).Name; ins$$anonymous$$d
Your answer
Follow this Question
Related Questions
ArrayList Transform type! 2 Answers
C# ArrayList access from other script 1 Answer
Problem with multi prefabs collision 1 Answer
how to change a variable from? an object in this array with a gui.button 0 Answers
Adding Waypoints using a List 2 Answers