Trouble with List.Count()

I’m having issues with List.Count() when I use it to find a position in a list. So for example:

firstPlacePlayerID = playerScores[playerScores.Count()].playersID;

The thing is that Debug.Log says there are nine entries in that list, so it’s not empty. I’m very confused with this. Can anyone help?

Collection indexing is zero-based. If you have 9 entries then the valid indexes will be 0-8. You need to subtract 1 to get the last one, or better yet:

firstPlacePlayerID = playerScores.Last().playersID;

Requires importing LINQ assembly in usings.

1 Like

Thanks, I did actually start with Last(), but I’m having trouble working out how to get to position Last() - 1. Meaning the second to last entry.

In their post they mentioned that getting the last value would be using the index of Count() - 1, so the natural conclusion is getting the second to last would be Count() - 2.

1 Like

Last() gives you the last entry. If you want a specific index other than Last() or First() you need to stick with the array indexing syntax, ie playerScores[7].

As stated above, arrays are ZERO based.

This means the above code will ALWAYS throw an index out of range exception.

This is how to index the very last entry:

playerScores[playerScores.Count() - 1]

It WILL throw an index out of range when you have zero entries (empty array).

It WILL throw a nullref if you fail to initialize playerScores.

1 Like