1. 程式人生 > >Unity排行榜,資料排序功能實現

Unity排行榜,資料排序功能實現

1.建立分數列表的父物體ScoreRankList,並新增Grid Layout Group元件自動排列UI。引數自己調

ScoreRankList
2.建立單條分數的資料組合ScoreData,並作為預製體,例項化使用。子物體包含排名,姓名,分數。

ScoreData

不囉嗦了,上程式碼。
排序邏輯:

/************************************************************
  FileName: SortScoreData.cs
  Author:Guido Kuo       Version :1.0        Date: 2018-10-16
  Description:資料排序
************************************************************/
namespace Assets.Scripts
{
    /// <summary>
    /// 排序邏輯
    /// </summary>
    public class SortScoreData : System.IComparable<SortScoreData>
    {
        public string Name;
        public int GameScore;
        public SortScoreData(string n, int s)
        {
            Name = n;
            GameScore = s;
        }
        public int CompareTo(SortScoreData other)
        {
            if (other == null)
                return 0;
            int value = other.GameScore - this.GameScore;
            return value;
        }
        public override string ToString()
        {
            return Name + " : " + GameScore.ToString();
        }
    }
}

排序操作:

/************************************************************
  FileName: RankScore.cs
  Author:Guido Kuo       Version :1.0        Date: 2018-10-16
  Description:資料排序
************************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

namespace Assets.Scripts
{
    public class RankScore : MonoBehaviour
    {
        private List<SortScoreData> _scoreDataList = new List<SortScoreData>(); //建立list,用來存Score資料
        private Transform _scoreDataParent;//父物體
        private GameObject _socreItem;
        private Button _sortButton;
        private InputField _nameField;
        private InputField _scoreField;
        private bool _isFirstReader = true;
        void Awake()
        {
            JudgementOrCreate();
            _scoreDataParent = GameObject.Find("/Canvas/ScoreRankList").transform;
            _sortButton= GameObject.Find("/Canvas/SortButton").GetComponent<Button>();
            _nameField = GameObject.Find("/Canvas/NameInputField").GetComponent<InputField>();
            _nameField.contentType = InputField.ContentType.Name;
            _scoreField = GameObject.Find("/Canvas/ScoreInputField").GetComponent<InputField>();
            _scoreField.contentType = InputField.ContentType.IntegerNumber;
        }

        void Start ()
        {
            if (_isFirstReader)
            {
                ReaderJson();
                _isFirstReader = false;
            }

            if (_scoreDataParent.childCount>0)
                for (int i = 0; i < _scoreDataParent.childCount; i++)
                {
                    GameObject a;
                    a = _scoreDataParent.GetChild(i).gameObject as GameObject;
                    Destroy(a);
                }

            _nameField.gameObject.SetActive(true);
            //_nameField.ActivateInputField();
            //_nameField.text = "";

            _scoreField.gameObject.SetActive(true);
            //_scoreField.text = null;

            _sortButton.transform.localPosition = new Vector3(0, -30f, 0);

            _sortButton.transform.GetChild(0).GetComponent<Text>().text = "SortData";

            ListenerInputField();
        }

        /// <summary>
        /// 監聽輸入
        /// </summary>
        void ListenerInputField()
        {
            _sortButton.onClick.RemoveAllListeners();
            _sortButton.onClick.AddListener(
                () =>
                {
                    SortSetSomething();
                    ScoreSort();
                });
            _nameField.onEndEdit.RemoveAllListeners();
            _nameField.onEndEdit.AddListener(delegate { _scoreField.ActivateInputField(); });
            _scoreField.onEndEdit.RemoveAllListeners();
            _scoreField.onEndEdit.AddListener(
                delegate
                {
                    _scoreDataList.Add(new SortScoreData(_nameField.text, Convert.ToInt32(_scoreField.text)));
                    SortSetSomething();
                    ScoreSort();
                });
        }
        /// <summary>
        /// 判斷是否有排序文件,如果沒有,建立一個空文件。本機地址,相對路徑。
        /// </summary>
        void JudgementOrCreate()
        {
            if (File.Exists(Application.persistentDataPath + "/RankingList.txt"))
                Debug.Log("已有檔案");
            else
                File.Open(Application.persistentDataPath + "/RankingList.txt", FileMode.Create);
            //Debug.Log(Application.persistentDataPath);路徑根目錄
        }

        /// <summary>
        /// 讀取資料流
        /// </summary>
        void ReaderJson()
        {
            //StreamReader sr = new StreamReader(Application.dataPath + "/Resources/RankingList.txt");//釋出之後還需自己建立RankingList.txt文件複製進Resource資料夾內,不方便,且易被更改。
            StreamReader sr = new StreamReader(Application.persistentDataPath + "/RankingList.txt");
            string nextLine;
            while ((nextLine = sr.ReadLine()) != null)
                _scoreDataList.Add(JsonUtility.FromJson<SortScoreData>(nextLine));
            sr.Close();//將所有儲存的分數全部存到list中   分行存入
        }

        /// <summary>
        /// 排序、例項化並重新寫入Json
        /// </summary>
        void ScoreSort()
        {
            _scoreDataList.Sort();

            //StreamWriter sw = new StreamWriter(Application.dataPath + "/Resources/RankingList.txt");//寫入資料流
            StreamWriter sw = new StreamWriter(Application.persistentDataPath + "/RankingList.txt");//寫入資料流

            if (_scoreDataList.Count > 10)//排序後刪除列表序列大於10的資料
                for (int i = 10; i <= _scoreDataList.Count; i++)
                    _scoreDataList.RemoveAt(i);

            foreach (SortScoreData t in _scoreDataList)
                sw.WriteLine(JsonUtility.ToJson(t));//重新寫入排序後的json資料

            sw.Close();//寫入結束

            InstantiateGo();

            for (int i = 0; i < _scoreDataList.Count; i++)
            {
                if (_scoreDataList[i].Name == _nameField.text)
                {
                    _scoreDataParent.GetChild(i).GetChild(0).GetComponent<Text>().color=Color.red;
                    _scoreDataParent.GetChild(i).GetChild(1).GetComponent<Text>().color=Color.red;
                    _scoreDataParent.GetChild(i).GetChild(2).GetComponent<Text>().color=Color.red;
                }
            }
        }

        /// <summary>
        /// 排序時的引數設定
        /// </summary>
        void SortSetSomething()
        {
            _nameField.gameObject.SetActive(false);
            _scoreField.gameObject.SetActive(false);
            _sortButton.transform.localPosition = new Vector3(361.5f, 205.5f, 0);
            _sortButton.transform.GetChild(0).GetComponent<Text>().text = "Back";
            _sortButton.onClick.RemoveAllListeners();
            _sortButton.onClick.AddListener( Start );
        }

        /// <summary>
        /// 例項化排名榜
        /// </summary>
        void InstantiateGo()//例項化排名榜
        {
            for (int i = 0; i < _scoreDataList.Count; i++)
            {
                _socreItem = Instantiate(Resources.Load<GameObject>("ScoreData")) as GameObject;
                _socreItem.gameObject.SetActive(true);
                _socreItem.transform.SetParent(_scoreDataParent, false);
                _socreItem.transform.Find("Number").GetComponent<Text>().text = (i + 1).ToString();
                _socreItem.transform.Find("Name").GetComponent<Text>().text = _scoreDataList[i].Name;
                _socreItem.transform.Find("Score").GetComponent<Text>().text = _scoreDataList[i].GameScore.ToString();
            }
        }
    }
}

工程下載:連結: https://pan.baidu.com/s/1EJUU09b1v7SwTeRZ7HGQUg 提取碼: nnv9