Originally wanted to use SortedDictionary to do the game in the leaderboard, the code is as follows:
usingUnityengine;usingSystem;usingSystem.Collections;usingSystem.Collections.Generic; Public classCustomcomparer<t>: icomparer<t>{Func<t, T,int>Mcomparerfunc; PublicCustomcomparer (Func<t, T,int>comparer) { This. Mcomparerfunc =comparer; } Public intCompare (t x, t y) {returnmcomparerfunc (x, y); }} Public classsorteddicttest:monobehaviour{SortedDictionary<string,int>Mleaderboard; voidStart () {Mleaderboard=Newsorteddictionary<string,int> (Newcustomcomparer<string> ((x, y) = =Mleaderboard[x]. CompareTo (Mleaderboard[y])); Mleaderboard.add ("Jhon",Ten); Mleaderboard.add ("Dark", +); Mleaderboard.add ("Ellie", -); foreach(varIteminchMleaderboard) {Debug.Log ("Name:"+ Item. Key +"Score:"+item. Value); } }}
The result is Unity's dead loop.
When you get a value in the dictionary, it calls the comparer. The comparator also calls the dictionary, causing a dead loop
And there is another problem with this usage, the sortable dictionary is the sort of key, which has a similar binary search mechanism.
In the leaderboard, but also by name matching, but also automatically sorted by the score, at this time is two sets of sorting mechanism, the dictionary internal Order confusion, the search speed is slower.
A workaround is also available, using a double dictionary to solve:
Public classsorteddicttest:monobehaviour{Dictionary<string,int>mscoredict; SortedDictionary<string,int>Mleaderboard; voidStart () {mscoredict=Newdictionary<string,int>(); Mleaderboard=Newsorteddictionary<string,int> (Newcustomcomparer<string> ((x, y) = =Mscoredict[x]. CompareTo (Mscoredict[y])); Mscoredict.add ("Jhon",Ten); Mscoredict.add ("Dark", +); Mscoredict.add ("Ellie", -); Mleaderboard.add ("Jhon",Ten); Mleaderboard.add ("Dark", +); Mleaderboard.add ("Ellie", -); foreach(varIteminchMleaderboard) {Debug.Log ("Name:"+ Item. Key +"Score:"+item. Value); } }}
Depending on the amount of data to weigh, directly using the list sort is not
Remember the improper use of sorteddictionary