[Game development practice] Unity recycles lists, supports irregular sizes (object pool | UGUI | ScrollRect | Demo source code)

I. Introduction

Hi everyone, I'm new.
A small friend asked Unityhow to implement an irregular circular reuse list in the question area.
insert image description here
I found GitHubthat someone has already implemented a version today, and the effect is good. The
GitHubaddress: https://github.com/aillieo/UnityDynamicScrollView
But this version has one BUG, I Made a fix, as explained in the third part of this article.

Good wheels are used by everyone. Today I will introduce how to use this version. The
final effect of this article is as follows
Please add image description

2. How to use

1. Create Scroll View

UICreate one on the node , Scroll Viewas
insert image description here
follows
insert image description here
Remove Scroll Viewthe component of the node Scroll Rect, as follows
insert image description here
Hang the ScrollViewcomponent or ScrollViewExcomponent in the code, I take the ScrollViewExcomponent as an example,

Note: It ScrollViewExinherits ScrollViewall the functions and has carried out targeted optimization. It will itemperform pagination. Setting the appropriate page size can get better performance.

insert image description here
After hanging the component, the effect is as follows,
insert image description here

2. Set Scroll View parameters

2.1. Adjust the width and height

Let's adjust Scroll Viewthe width and height first.
insert image description here

2.2, delete the Scrollbar slider

We see that Scroll Viewthere are two Scrollbarsliders, we don't want it, we
insert image description here
can directly delete the Scrollbar Horizontalsum under the child node. After Scrollbar Verticaldeleting,
insert image description here
we can see that there was space left Viewportbefore , but now there is no space , we need to adjust it to fill the whole , we Select and change both to , as followsScrollbarScrollbarViewportScroll View
insert image description here
ViewportRightBottom0
insert image description here

insert image description here

2.3. Set item template: Item Template

To display one by one in the list, you itemmust first make a itemtemplate. We Scroll Viewcreate one under the child node Image, rename it as itemfollows,
insert image description here
adjust itemthe width and height
insert image description here
as follows,
insert image description here
then select the Scroll Viewnode, set Item Templateit as just now item, and fill Default Item Sizein itemthe width and height as ,as follows
insert image description here

2.4. Set the object pool size: Pool Size

In order to prevent itemthe repeated creation and destruction of the list, the object pool is used here, and we need to set the size of the object pool Pool Size. If you keep stuffing objects into the object pool (just don’t take them out), after the object pool is full, you won’t continue to stuff objects into the object pool. We need to set a reasonable size of the object pool. It is recommended to be itemthe largest size that can be displayed in the visible area of ​​the list. Quantity 2倍, here I estimate that the visible area 10of ​​​​the list will be displayed at most item, then my object pool size is set to 20,
insert image description here

2.5, set the list arrangement direction

The list provides a 4kind of arrangement direction. You can see what it means when you look at the options. Here I take it Verticalas an example.
insert image description here

2.6. Set the page size: Page Size

If you are using a ScrollViewcomponent, there is no Page Sizesuch setting, only the ScrollViewExcomponent has this setting.
Why set up pagination? ScrollViewA copy is maintained in List<ScrollItemWithRect>, which is used to store itemthe coordinates and sizes.
insert image description here
Suppose your list has a huge amount of itemdata. You now have to insert a new one into the middle item. At this time, you need to recalculate the huge amount itemof coordinates and sizes, which is very expensive. Performance, the solution is to set up paging, and only maintain one page at a time item, which greatly improves performance.
It is recommended to set it to more than itemthe maximum number that can be displayed in the visible area of ​​the list 2倍. Here it is set to 30,
insert image description here

2.7. Other general settings

Set Contentand Viewport, as follows
insert image description here
Check Horizontalor according to the sliding direction Vertical, here I only need to slide vertically, so only check Vertical,
insert image description here

3. Add some elements to the item

Above our itembare, add some elements to it, and then fine-tune the overall interface, as follows The
insert image description here
node structure is as follows
insert image description here

4. Write test code

Create a MyTest.csscript as follows,

Note: TestScript.csand TestLargeAmount.csare the test scripts provided by the original author.

insert image description here
First define a data structure

// MyTest.cs

public struct RankItemData
{
    
    
	// 名次
    public int rank;
    // 名字
    public string name;
}

declare an Listobject to store the list data,

// MyTest.cs

List<RankItemData> testData = new List<RankItemData>();

Now let's write a method to construct some test data,

// MyTest.cs

private void Start()
{
    
    
	// 构造测试数据
    InitData();
}

private void InitData()
{
    
    
	// 构建50000个排名数据
    for (int i = 1; i <= 50000; ++i)
    {
    
    
        RankItemData data = new RankItemData();
        data.rank = i;
        data.name = "Name_" + i;
        testData.Add(data);
    }
}

Declare ScrollViewthe member object and ScrollViewset the callback function, as follows

// MyTest.cs

using System.Collections.Generic;
using UnityEngine;
using AillieoUtils;

public class MyTest : MonoBehaviour
{
    
    
	...
    public ScrollView scrollView;

	private void Start()
    {
    
    
    	...
    	
        scrollView.SetUpdateFunc((index, rect) =>
        {
    
    
            // TODO 更新item的UI元素
        });
        scrollView.SetItemSizeFunc((index) =>
        {
    
    
            // TODO 返回item的尺寸
            return Vector2.one;
        });
        scrollView.SetItemCountFunc(() =>
        {
    
    
            // TODO 返回数据列表item的总数
            return 0;
        });
    }
}

Next, we implement the specific content of the callback one by one.
updated element item,UI

// MyTest.cs

scrollView.SetUpdateFunc((index, rectTransform) =>
{
    
    
    // 更新item的UI元素
    RankItemData data = testData[index];
    rectTransform.gameObject.SetActive(true);
    rectTransform.Find("rankText").GetComponent<Text>().text = data.rank.ToString();
    rectTransform.Find("nameText").GetComponent<Text>().text = data.name;
    Button btn = rectTransform.Find("Button").GetComponent<Button>();
    btn.onClick.RemoveAllListeners();
    btn.onClick.AddListener(()=>{
    
    
        Debug.Log(data.name);
    });
});

The size of the return item, I want the itemheight of the top three to be higher, return Vector2(812, 180), the other return Vector2(812, 100),

// MyTest.cs

scrollView.SetItemSizeFunc((index) =>
{
    
    
    // 返回item的尺寸
    RankItemData data = testData[index];
    if(data.rank <= 3)
    {
    
    
        return new Vector2(812, 180);
    }
    else
    {
    
    
        return new Vector2(812, 100);
    }
});

returns itemthe total number of data lists,

// MyTest.cs

scrollView.SetItemCountFunc(() =>
{
    
    
    // 返回数据列表item的总数
    return testData.Count;
});

5. Run the test

We MyTest.cshang the script Canvason it and assign Scroll Viewmembers as follows,
insert image description here
then we itemhide it and
insert image description here
run it, the effect is as follows,
Please add image description
um, there is less space between itemand item, let's transform it.

6, item directly increases the interval

itemCreate one Imageand rename it to bg, set Anchorsto stretch-strech, set Topand Bottombit 2, so that there will be 2a gap of units up and down,
insert image description here
we delete our itemown Imagecomponents and re-run, the effect is as follows, to achieve our effect,
Please add image description
we can see, Although we have one list data 50000, UIonly a few itemare being reused in cycles, which is especially suitable for the display of lists with many data items.
insert image description here

3. BUG repair

During the test, I found one BUG. When using ScrollViewEx.csit, when turning pages, it will trigger frantically at the border, OnValueChangedresulting in fast page turning.
Please add image description
I am Demomaking a fix and adding a damping to avoid crazy page turning.
Please add image description

4. Demo source code

DemoI have uploaded the source code of this article GitCode, and interested students can download and study by themselves.
Address: https://codechina.csdn.net/linxinfa/UnityDynamicScrollView
insert image description here

5. Finished

Well, let's write it here.
I'm new, https://blog.csdn.net/linxinfa , a developer who works
silently in a small company , I hope I can help more people who want to learn, and encourage each other~UnityUnity

Guess you like

Origin blog.csdn.net/linxinfa/article/details/122019054