這篇文章給大家分享的是有關unity如何實現動態排行榜的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
在做2048游戲的時候要實現排行榜的功能:
1.超出顯示范圍可以通過滑動滾動條來上下查看
2.動態插入行
3.每次插入自動更新排名信息
其實和滑頁效果類似,只不過需要再加入排序的元素。
1.超出顯示范圍可以通過滑動滾動條來上下查看
滑頁效果(也就是超出顯示范圍如何顯示)見Unity實現滑動更換界面的效果
排行榜的rank、Viewport、content同滑頁中的組件配置。
排行榜是由排名、名字、分數組成的。
滾動條的滑動是每一行每一行形式的,所以給容器Content加水平布局組件和容器大小的自適應。
參數都是一點點試出來的,沒別的辦法==
2.動態插入行
動態插入當然要用預制件了:也就是上圖中的line
關于line,每一行顯然是豎直的布局(排名、名字、分數),所以加豎直布局組件,line是image,其下有三個Text(排名、名字、分數):
參數都是一點點試出來的,沒別的辦法==
接下來就要用代碼插入了,插入的調用在3中(因為游戲中的需求是輸入名稱點登陸后再在排行榜中插入),并且更新排行榜(更新的代碼在3中,其實就是找到當前分數在排行榜中的位置,然后插入,在遍歷其后元素讓他們的排名都比前一位+1,最后只需要更新排名、名字、分數即可,并不用destroy)
/// <summary> /// 生成UI元素 /// </summary> public void CreateNewLine(PlayerNode tmp) { //法1:通過GameObject //法2:通過預制件 GameObject l = Instantiate(line); l.transform.SetParent(transform); l.transform.GetChild(0).GetComponent<Text>().text = tmp.Rank.ToString(); l.transform.GetChild(1).GetComponent<Text>().text = tmp.Name; l.transform.GetChild(2).GetComponent<Text>().text = tmp.Score.ToString(); } public void updateRank(List<PlayerNode> players) { for(int i = 0; i < transform.childCount; i++) { //Destroy(transform.GetChild(i).gameObject); Transform l = transform.GetChild(i); l.GetChild(0).GetComponent<Text>().text = players[i].Rank.ToString(); l.GetChild(1).GetComponent<Text>().text = players[i].Name; l.GetChild(2).GetComponent<Text>().text = players[i].Score.ToString(); } //for(int i = 0; i < players.Count; i++) //{ // CreateNewLine(players[i]); //} }
3.每次插入自動更新排名信息
public class PlayerNode { public string Name { get; set; } public int Score { get; set; } public int Rank { get; set; } public PlayerNode(string name, int score, int rank) : this() { this.Name = name; this.Score = score; this.Rank = rank; } public PlayerNode() { } }
然后存在容器中,每次插入新行就更新所有行的排名:
public List<PlayerNode> players = new List<PlayerNode>(); /// <summary> /// 當點擊登錄時 /// </summary> public void Load() { if (inputField.text != null) { PlayerNode tmp = new PlayerNode(inputField.text, int.Parse(GC.NowScore.text), 1); rc.CreateNewLine(tmp); if (isFirst)//如果是第一次插入 { players.Add(tmp); isFirst = false; } else { int rankIndex = 0; for (int i = 0; i < players.Count; i++) { if (tmp.Score > players[i].Score) { rankIndex = i; tmp.Rank = i + 1; players.Insert(rankIndex, tmp); rankIndex = i + 1; break; } } if (rankIndex == 0) { tmp.Rank = players.Count + 1; players.Insert(players.Count, tmp); } else { for (int i = rankIndex; i < players.Count; i++) { players[i].Rank = players[i - 1].Rank + 1; } } } rc.updateRank(players); } //if (players.Count > 2) //{ // for(int i = 0; i < players.Count; i++) // { // print(players[i].Rank + "-" + players[i].Name + "-" + players[i].Score); // } //} gameObject.SetActive(false); } }
感謝各位的閱讀!關于“unity如何實現動態排行榜”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。