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

来源:互联网 发布:足彩关注软件 编辑:程序博客网 时间:2024/05/29 07:25

具体效果

大体方法:创建一个分数类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主界面时

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


当游戏结束分数结算时

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

当用户点击排行榜按钮时

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

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

public class Score : System.IComparable<Score>{    public string name;    public int score;    public Score(string n, int s) { name = n; score = s; }    public int CompareTo(Score other)    {        if (other == null)            return 0;        int value = other.score - this.score;        return value;    }    public override string ToString()//debug用    {        return name + " : " + score.ToString();    }}

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

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

主要是用到了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,还可以实现很多功能,大坑啊。



原创粉丝点击