当前位置:   article > 正文

unity本地分数排行榜简单解决方案(Json)_untiy 排行榜

untiy 排行榜

具体效果

大体方法:创建一个分数类Score和一个分数类的容器List<Score>,和一个json.txt用来存储所有的分数(最多显示10条分数)。进入主菜单时读取txt将分数全部读到list中,当用户点击排行榜显示按钮时从list中加载出来;在游戏中结算分数时实例化一个分数类并Add到List中,并排一下序,把分数最小的元素Remove掉(一拍大腿,为什么不用优先队列呢!!不过那得自己实现),并输出到文本中。什么时候读和输出其实可以很随意,能实现效果就好,毕竟运算的元素不多。

方法

准备工作:先创建一个所有分数的父物体Item,在上面挂上GridLayoutGroup

这个是用来让分数Prefab自动排版,设置参数如图

然后制作一个分数Prefab,一个空物体下面有3个text子物体分别对应Number,Name,Score

准备工作完事,然后是代码  

 

  List<Score> scoreList = new List<Score>(); //创建list,用来存Score

 

 

当用户进入游戏i主界面时

 

  1. StreamReader sr = new StreamReader(Application.dataPath + "/Resources/RankingList.txt");
  2. string nextLine;
  3. while ((nextLine = sr.ReadLine()) != null)
  4. {
  5. scoreList.Add(JsonUtility.FromJson<Score>(nextLine));
  6. }
  7. sr.Close();//将所有存储的分数全部存到list中

 

 

当游戏结束分数结算时

 

        scoreList.Add(new Score(Name, numScore));//分数名字直接调变量,不用给出细节分数名字直接调变量,不用给出细节

 

 

 

当用户点击排行榜按钮时

 

  1. scoreList.Sort();
  2. StreamWriter sw = new StreamWriter(Application.dataPath + "/Resources/RankingList.txt");
  3. if (scoreList.Count > 10) for (int i = 10; i < scoreList.Count;i++ ) scoreList.RemoveAt(i);
  4. for (int i = 0; i < scoreList.Count; i++)
  5. {
  6. sw.WriteLine(JsonUtility.ToJson(scoreList[i]));
  7. Debug.Log(scoreList[i].ToString());
  8. }
  9. sw.Close();


这样,list中就存了最多10条分数记录了,排序方法需要实现接口。下面是Score类的定义

 

 

  1. public class Score : System.IComparable<Score>
  2. {
  3. public string name;
  4. public int score;
  5. public Score(string n, int s) { name = n; score = s; }
  6. public int CompareTo(Score other)
  7. {
  8. if (other == null)
  9. return 0;
  10. int value = other.score - this.score;
  11. return value;
  12. }
  13. public override string ToString()//debug用
  14. {
  15. return name + " : " + score.ToString();
  16. }
  17. }


list的部分就大功告成了,最后是加载Prefab

 

 

  1. for (int i = 0; i < scoreList.Count; i++)
  2. {
  3. GameObject item = Instantiate(Item.gameObject);
  4. item.gameObject.SetActive(true);
  5. item.transform.SetParent(Item.parent, false);
  6. item.transform.Find("Number").GetComponent<Text>().text = (i + 1).ToString();
  7. item.transform.Find("Name").GetComponent<Text>().text = scoreList[i].name;
  8. item.transform.Find("Score").GetComponent<Text>().text = scoreList[i].score.ToString();
  9. }


主要是用到了unity自己的JsonUtility,将类输出成json的字符串,同样还能将json的字符串转化成类,非常方便。

 

{"name":"hjkhjk","score":26}
{"name":"zzz","score":15}
{"name":"213","score":9}
{"name":"ad","score":6}
{"name":"g","score":6}
{"name":"3333","score":3}
{"name":"9","score":0}
{"name":"qwe","score":0}
{"name":"l","score":0}
{"name":"9","score":0}

 

通过JsonUtility,还可以实现很多功能,大坑啊。

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/369463
推荐阅读
相关标签
  

闽ICP备14008679号