Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Picking the 3 first players from a Dictionary

Discussion in 'Scripting' started by strongbox3d, Sep 3, 2020.

  1. strongbox3d

    strongbox3d

    Joined:
    May 8, 2012
    Posts:
    816
    Hello guys,

    I made this multiplayer game where up to 4 players can compete hunting fish. I have a dictionary that contains the players name as keys and the score as values. When the time runs out, I want to be able to show what players are the first, second, and third places.

    Can someone here, help me to figure out how to sort, or compare, the values in the dictionary so I can select each player who won any of those places?

    I have google this without any good results.

    Regards,
    Carlos
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    9,071
    Bunny83 likes this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    188
    A Dictionary is not an ordered collection and can't really be sorted. However you can get the KeyValuePairs it contains as an array or List and just sort that.

    Code (CSharp):
    1.  
    2.         Dictionary<string, int> playerScores = new Dictionary<string, int>();
    3.         // copy all KeyValuePairs into a List
    4.         var list = new List<KeyValuePair<string, int>>(playerScores);
    5.         // Sort them based on the "Value"
    6.         list.Sort((a,b)=>a.Value.CompareTo(b.Value));
    7.  
     
    Kurt-Dekker likes this.
  4. strongbox3d

    strongbox3d

    Joined:
    May 8, 2012
    Posts:
    816
    Hello guys,

    Thank you for your reply!

    Regards,
    Carlos
     
unityunity