1.創(chuàng)建分數(shù)列表的父物體ScoreRankList,并添加Grid Layout Group組件自動排列UI。參數(shù)自己調(diào)

01.png
2.創(chuàng)建單條分數(shù)的數(shù)據(jù)組合ScoreData,并作為預制體,實例化使用。子物體包含排名,姓名,分數(shù)。

image.png
排序邏輯:
/************************************************************
FileName: SortScoreData.cs
Author:Guido Kuo Version :1.0 Date: 2018-10-16
Description:數(shù)據(jù)排序
************************************************************/
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:數(shù)據(jù)排序
************************************************************/
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>(); //創(chuàng)建list,用來存Score數(shù)據(jù)
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>
/// 監(jiān)聽輸入
/// </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>
/// 判斷是否有排序文檔,如果沒有,創(chuàng)建一個空文檔。本機地址,相對路徑。
/// </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>
/// 讀取數(shù)據(jù)流
/// </summary>
void ReaderJson()
{
//StreamReader sr = new StreamReader(Application.dataPath + "/Resources/RankingList.txt");//發(fā)布之后還需自己創(chuàng)建RankingList.txt文檔復制進Resource文件夾內(nèi),不方便,且易被更改。
StreamReader sr = new StreamReader(Application.persistentDataPath + "/RankingList.txt");
string nextLine;
while ((nextLine = sr.ReadLine()) != null)
_scoreDataList.Add(JsonUtility.FromJson<SortScoreData>(nextLine));
sr.Close();//將所有存儲的分數(shù)全部存到list中 分行存入
}
/// <summary>
/// 排序、實例化并重新寫入Json
/// </summary>
void ScoreSort()
{
_scoreDataList.Sort();
//StreamWriter sw = new StreamWriter(Application.dataPath + "/Resources/RankingList.txt");//寫入數(shù)據(jù)流
StreamWriter sw = new StreamWriter(Application.persistentDataPath + "/RankingList.txt");//寫入數(shù)據(jù)流
if (_scoreDataList.Count > 10)//排序后刪除列表序列大于10的數(shù)據(jù)
for (int i = 10; i <= _scoreDataList.Count; i++)
_scoreDataList.RemoveAt(i);
foreach (SortScoreData t in _scoreDataList)
sw.WriteLine(JsonUtility.ToJson(t));//重新寫入排序后的json數(shù)據(jù)
sw.Close();//寫入結(jié)束
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>
/// 排序時的參數(shù)設置
/// </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();
}
}
}
}
工程名字:RankScore.unitypackage