Search code examples
databaselistunity-game-enginearraylistuser-controls

Index of list elements for user data


Ive a specific question:

In my game differend users can add an account to a local based app. Basically i thougth about saving names, scores and choosed avatar images to three differend lists. But i relized following:

When adding a value (f.e. "0") to a list called userScore, unity debugs same values at the same index, but the count value is correct. Lets say i add five times "0" to my userScore list, the userScore.Count = 5, but when iam using following debug code:

 for (int i = 0; i < userScore.Count; i++)
         {
             Debug.Log("Score " + userScore[i] + "with Index " + userScore.IndexOf(userScore[i]) );
     }

i get the result 0 with index 0 (five times) - but it should be

0 with index 0 0 with index 1 0 with index 2 0 with index 3 0 with index 4

Can someone explain me why? And has someone a better idea to make player stats with specific values? Users can be added and deleted, so i would have to have a dynamic system where i can get the player name, score and choosed avatar. In my opinion i would achieve this with those lists, but probably there is a better way.

thank you very much!


Solution

  • Why making things complicated?

    for (int i = 0; i < userScore.Count; i++)
    {
        Debug.Log("Score " + userScore[i] + "with Index " + i );
    }
    

    As indicated in the documentation IndexOf returns the index of the first occurrence of a value in the List. If you have a list containing [1, 1, 1, 1], calling IndexOf(1) will return 0, because 1 is found at index 0, no matter how many times you call IndexOf


    I advise you to use a struct / class in order to contain the data of your users since you plan to manipulate more information:

    public struct UserData
    {
        public int ID;
        public string Name;
        public int Score;
        public int AvatarIndex;
    }
    
    // ...
    
    public List<UserData> UserData;
    
    for (int i = 0; i < UserData.Count; i++)
    {
        Debug.Log("Score " + UserData.Score[i] + "with Index " + i );
    }