Unity3D 实现本地排行榜功能

       大家在玩游戏的时候,无论是大型的网游还是普通的手游都会遇见游戏结束时的排行榜,那么这个排行榜是怎么实现的,最近研究了一番。下面让大家看看效果,没有UI,就是简单的Image与Text。

第一个是名次,第二个是名字,第三个是分数,第四个是时间。上面那个是添加新的记录。名字是在前面的场景中拿到的,如果测试,可以在当前的场景中直接把Text改为InputField即可。

下面是我用到的代码。

1.先搭建基本的UI。大家可以自由发挥。

2.这是基本的声明。

    //输入需要排行的信息-在实际逻辑中从外部获取再展示
    public InputField inputField;
    //提交需要排行信息
    public Button button;

    public GameObject prefabShow;
    public Image parentsShow;
    public Image parentsShowUI;
    public Text textName;

 3.在初始化时我们拿到玩家的名字和对事件绑定。就是提交按钮触发的事件。 

     void Start ()
     {
         textName.text = Global.PlayerName;
         button.GetComponent<Button>().onClick.AddListener(InputOK);
     }

     void InputOK()
     {
        Global.SkillCount = int.Parse(inputField.text);
        string PlayerResultDate = ResultToJson(Global.PlayerName, Global.SkillCount);
        SaveString(PlayerResultDate);
        DictionarySort(GetJsonDate()); 
    }

2.首先需要知道,既然是排行榜,一定涉及到了数据持久化,那么,在这我用的是Json,对于Json的操作我就不在这里赘述了。我存取的方式是将名字分数以及时间存在本地。

    //将数据转化成Json
    public string ResultToJson(string Name, int NowCount)
    {
        StringBuilder sb = new StringBuilder();
        JsonWriter WriteDate = new JsonWriter(sb);
        WriteDate.WriteObjectStart();
        WriteDate.WritePropertyName("Name");
        WriteDate.Write(Name + "|" + DateTime.Now.ToShortTimeString());
        WriteDate.WritePropertyName("Count");
        WriteDate.Write(NowCount);
        WriteDate.WriteObjectEnd();
        return sb.ToString();
    }

    //下面的方法就是保存在本地
    private void SaveString(string str)
    {
        FileInfo fi = new FileInfo(Application.dataPath + "/Resources/Json.txt");
        StreamWriter sw = null;
        if (fi.Exists)
        {
            sw = fi.AppendText();
        }
        else
        {
            sw = fi.CreateText();
        }
        sw.WriteLine(str);
        sw.Close();
    }

   //下面的方法是获取Json数据
   public Dictionary<string, int> GetJsonDate()
    {
        FileStream fi = new FileStream(Application.dataPath + "/Resources/Json.txt", FileMode.Open);
        Dictionary<string, int> jsonDate = new Dictionary<string, int>();
        if (fi.CanRead)
        {
            StreamReader sw = new StreamReader(fi);
            string jsonStr;
            while ((jsonStr = sw.ReadLine()) != null)
            {
                JsonData data = JsonMapper.ToObject(jsonStr);
                jsonDate.Add(data["Name"].ToString(), int.Parse(data["Count"].ToString()));
            }
        }
        return jsonDate;
    }

   //这个方法是把获取的Json数据排序并且显示出来
   private void DictionarySort(Dictionary<string, int> dic)
    {
        if (dic.Count > 0)
        {
            List<KeyValuePair<string, int>> lst = new List<KeyValuePair<string, int>>(dic);
            lst.Sort(delegate(KeyValuePair<string, int> s1, KeyValuePair<string, int> s2)
            {
                return s2.Value.CompareTo(s1.Value);
            });
            //parentsShow.rectTransform.sizeDelta = new Vector2(600, lst.Count * 100);
            //parentsShowUI.GetComponent<Mask>().enabled = true;
            //parentsShowUI.GetComponentInChildren<Scrollbar>().value = 1;
            dic.Clear();
            float i = 1, r = 1, g = 1, b = 0;
            foreach (KeyValuePair<string, int> kvp in lst)
            {
                if (i <= 3)
                {
                    string[] Key = kvp.Key.Split('|');
                    GameObject ga = Instantiate(prefabShow, parentsShow.transform.position, Quaternion.identity) as GameObject;
                    ga.transform.parent = parentsShow.transform;
                    r -= 0.2f;
                    g -= 0.2f;
                    b -= 0.2f;
                    Debug.Log(r + g + b);
                    Text[] Children = ga.GetComponentsInChildren<Text>();
                    Children[0].color = new Color(r, g, b);
                    Children[1].color = new Color(r, g, b);
                    Children[2].color = new Color(r, g, b);                
                    Children[3].color = new Color(r, g, b);
                  
                 
                    Children[1].text = Key[0];
                    Children[3].text = kvp.Value.ToString();
                    Children[2].text = Key[1];
                    Children[0].text = (i++).ToString();
                }
                else
                {
                    string[] Key = kvp.Key.Split('|');
                    GameObject ga = Instantiate(prefabShow, parentsShow.transform.position, Quaternion.identity) as GameObject;
                    ga.transform.parent = parentsShow.transform;
                    Text[] Children = ga.GetComponentsInChildren<Text>();
                    Children[1].text = Key[0];
                    Children[3].text = kvp.Value.ToString();
                    Children[2].text = Key[1];
                    Children[0].text = (i++).ToString();
                }      
            }
        }
    }

好了,这个排行榜的主要逻辑部分就完成了,如果有什么写得不对的地方 ,希望大家在下方留言,一起进步与提升。


评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值