UGui realizes ranking, list data assignment, sorting, ascending and descending.

Posted by Sakesaru on Tue, 04 Jan 2022 20:11:41 +0100

catalogue

UGUI sliding list implementation:

Steps:

The following is the code to automatically generate list items and assign and sort them:

UGUI sliding list implementation:

Steps:

First step
Create an Image and rename it to“ Scroll View ", add Scroll Rect Component, set component: uncheck horziontal (move horizontally). Add again Mask Component, uncheck Show Mask Graphic.

Step 2
Add Image under ScrollView as the background of the list and change it to "Viewport".

Step 3
Add an Image under the viewport as the parent object of the list item and change it to "content". The size of the content should be consistent with the background of the viewport.

Set the anchor point to and Pivot, as shown in the figure below

Add VerticalLayoutGroup component, as shown in the following figure

Add the ContentSizeFitter component, as shown in the following figure

Step 4

Add the ScollBar slider and place it in the appropriate position. The diversion property can set the sliding direction of the slider and choose to use it according to your needs.  

Step 5
Go back to the ScrollRect component of ScrollView. Make the following settings.

 

Step 6

Under Content, create a new image as a list item and change it to "item". The width setting is consistent with the Content and is more beautiful. In item, set a text box and image according to your needs to display your own Content, and then drag it into a preform.

Step 7

Create two drop-down boxes: sort data type and sort type

 

In the Template, you can set the background text and other information of the drop-down options:

 

The above completes the basic ui construction of the slider.

Reference link: Unity implements Scrollview - ugui

The following is the code to automatically generate list items and assign and sort them:

1. Create ItemData list data class first without mounting.

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

namespace ReportCard
{
    public class ItemData
    {
        /// <summary>
        ///User name
        /// </summary>
        public string UserName { get; }
        /// <summary>
        ///User id
        /// </summary>
        public string Id { get; }
        /// <summary>
        ///Current score
        /// </summary>
        public float CurrentScore { get; }
        /// <summary>
        ///Last round score
        /// </summary>
        public float LastScore { get; }
        /// <summary>
        ///Highest score
        /// </summary>
        public float TopScore { get; }


        public ItemData(string userName,string id, float currentScore, float lastScore=0,float topScore=0)
        {
            UserName = userName;
            Id = id;
            CurrentScore = currentScore;
            LastScore = lastScore;
            TopScore = topScore;
        }
    }
}

2. Create a ScrollView script, mount it on the corresponding ScrollView of the panel, and then drag the corresponding object to the script public variable according to the name.

 

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

namespace ReportCard
{
    public class ScrollView : MonoBehaviour
    {
        /// <summary>
        ///Slide bar
        /// </summary>
        [SerializeField] Scrollbar scrollbar;
        /// <summary>
        ///List box
        /// </summary>
        [SerializeField] Transform Content;
        /// <summary>
        ///List item preform
        /// </summary>
        [SerializeField] GameObject cellPrefab = default;
        /// <summary>
        ///Sort type drop-down box
        /// </summary>
        [SerializeField] Dropdown sortingType = default;
        /// <summary>
        ///Sort by drop-down box
        /// </summary>
        [SerializeField] Dropdown Sortord = default;

        /// <summary>
        ///Cache item
        /// </summary>
        List<ItemData> cacheDatas = new List<ItemData>();
        void Start()
        {
            //Event triggered by drop-down box option change
            sortingType.onValueChanged.AddListener(_ => SetSortord());
            sortingType.value = 0;

            Sortord.onValueChanged.AddListener(_ => SetSortord());
            Sortord.value = 0;
        }
        /// <summary>
        ///Sort by drop-down box event and sort type drop-down box event
        /// </summary>
        private void SetSortord()
        {
            if (cacheDatas.Count == 0) //Returns if the list item is 0
            {
                return;
            }
            SetReportCardData(cacheDatas);
        }

        /// <summary>
        ///Design leaderboard data
        /// </summary>
        /// <param name="itemDatas"></param>
        public void SetReportCardData(List<ItemData> itemDatas)
        {
            cacheDatas = itemDatas;//Cache external list data
            Cell cell;//List item
            DataProcessing(cacheDatas, () =>
            {
                if (Content.childCount != 0) //Judge whether the list item already exists in the list. If it exists, it will be re assigned, and if not, it will be created
                {
                    for (int i = 0; i < cacheDatas.Count; i++) //Loop through the script on the list item and re assign it
                    {
                        cell = Content.GetChild(i).GetComponent<Cell>();
                        cell.SetItemInfo(new ItemData(cacheDatas[i].UserName, cacheDatas[i].Id, cacheDatas[i].CurrentScore, cacheDatas[i].LastScore, cacheDatas[i].TopScore), i + 1);
                    }
                }
                else
                {
                    for (int i = 0; i < cacheDatas.Count; i++)  //Instantiate list items and assign values
                    {
                        cell = Instantiate(cellPrefab, Content).GetComponent<Cell>();
                        cell.SetItemInfo(new ItemData(cacheDatas[i].UserName, cacheDatas[i].Id, cacheDatas[i].CurrentScore, cacheDatas[i].LastScore, cacheDatas[i].TopScore), i + 1);
                    }
                }
                scrollbar.value = 1;//Each time you change the list data, slide the list to the top.
            });
        }
        /// <summary>
        ///Data sorting processing
        /// </summary>
        /// <param name="itemDatas"></param>
        /// <param name="action"></param>
        void DataProcessing(List<ItemData> itemDatas, Action action)
        {
            float currentScore = 0;
            float nextScore = 0;
            //Use bubble sort
            for (int i = 0; i < itemDatas.Count - 1; i++) //The outer cycle requires n - 1 cycles
            {
                for (int j = 0; j < itemDatas.Count - 1 - i; j++)
                {
                    switch (sortingType.value) //Sort the corresponding data according to the drop-down box type
                    {
                        case 0:
                            currentScore = itemDatas[j].CurrentScore;
                            nextScore = itemDatas[j + 1].CurrentScore;
                            break;
                        case 1:
                            currentScore = itemDatas[j].LastScore;
                            nextScore = itemDatas[j + 1].LastScore;
                            break;
                        case 2:
                            currentScore = itemDatas[j].TopScore;
                            nextScore = itemDatas[j + 1].TopScore;
                            break;
                        default:
                            break;
                    }
                    if (Sortord.value == 0)//Determine whether the order is ascending or descending according to the type of drop-down box
                    {
                        if (currentScore < nextScore)
                        {
                            ItemData data = itemDatas[j + 1];
                            itemDatas[j + 1] = itemDatas[j];
                            itemDatas[j] = data;
                        }
                    }
                    else
                    {
                        if (currentScore > nextScore)
                        {
                            ItemData data = itemDatas[j + 1];
                            itemDatas[j + 1] = itemDatas[j];
                            itemDatas[j] = data;
                        }
                    }
                }
            }
            action.Invoke();
        }
        /// <summary>
        ///Clear data
        /// </summary>
        public void ClearData()
        {
            if (Content.childCount != 0)
            {
                cacheDatas.Clear();//Cache data clearing
                for (int i = 0; i < Content.childCount; i++)//List item clear
                {
                    Destroy(Content.GetChild(i).gameObject);
                }
            }
        }
    }
}

3. Create a Cell class and mount it on the list item preform

 

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

namespace ReportCard
{
    public class Cell : MonoBehaviour
    {
        [SerializeField] Image Bg;
        [SerializeField] Text rankingText;
        [SerializeField] Text userNameText;
        [SerializeField] Text userIdText;
        [SerializeField] Text currentScoreText;
        [SerializeField] Text lastScoreText;
        [SerializeField] Text topScoreText;
        [HideInInspector] public ItemData data;
        public void SetItemInfo(ItemData itemData, int ranking)
        {
            data = itemData;
            rankingText.text = ranking.ToString(); ;
            userNameText.text = data.UserName;
            string id = data.Id.Substring(data.Id.Length - 4, 4);
            userIdText.text = "ID:**************" + id;
            currentScoreText.text = data.CurrentScore.ToString();
            lastScoreText.text = data.LastScore.ToString();
            topScoreText.text = data.TopScore.ToString();
        }

    }
}

4. Create a ReportCardManager class for application testing, and call the Test method in Start.

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using EasingCore;
using System;
using ReportCard;
/// <summary>
///Transcript management
/// </summary>
public class ReportCardManager : MonoBehaviour
{
    ScrollView scrollView;
    GameObject ReportCardWindow;
    /// <summary>
    ///Cache item
    /// </summary>
    List<ItemData> cacheDatas = new List<ItemData>();
    void Start()
    {
        ReportCardWindow = transform.Find("ReportCardWindow").gameObject;
        scrollView = ReportCardWindow.GetComponentInChildren<ScrollView>();
        ReportCardWindow.transform.Find("CloseButton").GetComponent<Button>().onClick.AddListener(HideReportCardWindow);
        Test();
    }
    public void Test()
    {
        //Test create false data
        List<ItemData> datas = new List<ItemData>();
        datas.Add(new ItemData("Liu ran", "120109198312216535", 100, 80, 90));
        datas.Add(new ItemData("Xu Shuang", "210105198305032224", 89, 789, 77));
        datas.Add(new ItemData("Zhou Xin", "430681198811050058", 150, 720, 99));
        datas.Add(new ItemData("Wang Xueyun", "310106198705064015", 350, 460, 11));
        datas.Add(new ItemData("Wei Chao", "610104198511107337", 88, 880, 900));
        datas.Add(new ItemData("Guo Shengwei", "41282919861205005X", 520, 442, 252));
        datas.Add(new ItemData("Yang Jianjun", "510703198206262217", 752, 840, 752));
        datas.Add(new ItemData("Liu Yang", "320402198509133432", 752, 880, 41));
        datas.Add(new ItemData("Wang Jianyao", "640203198201171015", 752, 578, 11));
        datas.Add(new ItemData("Wei Chao", "50024119890802531X", 842, 54, 900));
        ShowReportCardWindow(datas);
    }
    /// <summary>
    ///Display interface
    /// </summary>
    ///< param name = "data" > user data < / param >
    public void ShowReportCardWindow(List<ItemData> datas)
    {
        if (cacheDatas.Count != 0)
        {
            cacheDatas.Clear(); //Clear cache
        }
        for (int i = 0; i < datas.Count; i++)//The externally transmitted data is not necessarily of ItemData type, so the data is converted
        {
            //Add the corresponding data to your list user name user id the highest score in the history of the last round of scores
            cacheDatas.Add(new ItemData(datas[i].UserName, datas[i].Id, datas[i].CurrentScore, datas[i].LastScore, datas[i].TopScore));
        }
        //Set UI list transfer data
        scrollView.SetReportCardData(cacheDatas);
        //Interface display
        ReportCardWindow.SetActive(true);
    }
    /// <summary>
    ///Hide interface
    /// </summary>
    public void HideReportCardWindow()
    {
        //Interface hiding
        ReportCardWindow.SetActive(false);
        //data dump
        scrollView.ClearData();
    }

}

 5. Disable ReportCardWindow and start running

I can't read it, but I can write it privately!

Topics: Unity UGUI