unity无限滚动制作排行榜

实现无限拖拽的方法.脚本挂载在VerticalScroll 上.组件设置如下,特别是锚点的设置


TIM图片20171204101740.png
TIM图片20171204101745.png

使用方法只需要调用以下方法就好

  void Start()
  {
  cb = CachePoolFactory.GetPool("GiftPool");
        ReflashList();
        infinityGridLayoutGroup = GameRecordBG.transform.GetComponent<InfinityGridLayoutGroup>();

        infinityGridLayoutGroup.updateChildrenCallback = UpdateChildrenCallback;

    }
    private void ReflashList()
    {
        amount = LuluResultInfo.Instance().record_gift.Count;
        infinityGridLayoutGroup = GameRecordBG.transform.GetComponent<InfinityGridLayoutGroup>();
        infinityGridLayoutGroup.SetAmount(amount);
        infinityGridLayoutGroup.CreateItem(RecordPerfab, GameRecordBG.transform, 9, cb);
        infinityGridLayoutGroup.Init();

    }

对象池使用完一定要记得释放

 private void OnDestroy()
    {
        cb.Clear();
    }

InfinityGridLayoutGroup脚本如下

/**************************
 * 文件名:InfinityGridLayoutGroup.cs;
 * 文件描述:无限滚动GridLayoutGroup,动态创建滚动Item;
 * 实现无限滚动,需要的最少的child数量。屏幕上能看到的+一行看不到的,比如我在屏幕上能看到 2 行,每一行 2 个。则这个值为 2行*2个 + 1 行* 2个 = 6个。
 * 创建日期:2016/05/31;
 * Author:ThisisGame;
 * Page:https://github.com/ThisisGame/InfinityGridLayoutGroup
 ***************************/

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

[RequireComponent(typeof(GridLayoutGroup))]
[RequireComponent(typeof(ContentSizeFitter))]
public class InfinityGridLayoutGroup : MonoBehaviour
{

    [SerializeField]
    int minAmount = 0;//实现无限滚动,需要的最少的child数量。屏幕上能看到的+一行看不到的,比如我在屏幕上能看到 2 行,每一行 2 个。则这个值为 2行*2个 + 1 行* 2个 = 6个。

    RectTransform rectTransform;

    GridLayoutGroup gridLayoutGroup;
    ContentSizeFitter contentSizeFitter;

    ScrollRect scrollRect;

    List<RectTransform> children = new List<RectTransform>();

    Vector2 startPosition;

    int amount = 0;

    public delegate void UpdateChildrenCallbackDelegate(int index, Transform trans);
    public UpdateChildrenCallbackDelegate updateChildrenCallback = null;

    int realIndex = -1;
    int realIndexUp = -1; //从下往上;

    bool hasInit = false;

    public bool HasInit
    {
        get { return hasInit; }
    }
    Vector2 gridLayoutSize;
    Vector2 gridLayoutPos;
    Dictionary<Transform, Vector2> childsAnchoredPosition = new Dictionary<Transform, Vector2>();
    Dictionary<Transform, int> childsSiblingIndex = new Dictionary<Transform, int>();

    private Action<GameObject> itemCallback;

    public Action<GameObject> ItemCallback
    {
        get { return itemCallback; }
        set { itemCallback = value; }
    }

    private Action initCompleteCallback;

    public Action InitCompleteCallback
    {
        get { return initCompleteCallback; }
        set { initCompleteCallback = value; }
    }

    void Awake()
    {
        gridLayoutGroup = GetComponent<GridLayoutGroup>();
        contentSizeFitter = GetComponent<ContentSizeFitter>();
    }

    // Use this for initialization
    void Start()
    {
        //StartCoroutine(InitChildren());
        scrollRect = transform.parent.GetComponent<ScrollRect>();
        rectTransform = GetComponent<RectTransform>();
    }

    IEnumerator InitChildren()
    {
        yield return 0;

        if (!hasInit)
        {
            //获取Grid的宽度;

            gridLayoutGroup.enabled = false;
            contentSizeFitter.enabled = false;

            gridLayoutPos = rectTransform.anchoredPosition;
            gridLayoutSize = rectTransform.sizeDelta;


            //注册ScrollRect滚动回调;


            scrollRect.onValueChanged.AddListener((data) => { ScrollCallback(data); });

            //获取所有child anchoredPosition 以及 SiblingIndex;
            for (int index = 0; index < transform.childCount; index++)
            {
                Transform child = transform.GetChild(index);
                RectTransform childRectTrans = child.GetComponent<RectTransform>();
                childsAnchoredPosition.Add(child, childRectTrans.anchoredPosition);
                childsSiblingIndex.Add(child, child.GetSiblingIndex());
            }
        }
        else
        {
            contentSizeFitter.enabled = false;
            gridLayoutGroup.enabled = false;
            rectTransform.anchoredPosition = gridLayoutPos;
            gridLayoutSize = rectTransform.sizeDelta;
            rectTransform.sizeDelta = gridLayoutSize;

            children.Clear();

            realIndex = -1;
            realIndexUp = -1;

            //children重新设置上下顺序;
            foreach (var info in childsSiblingIndex)
            {
                info.Key.SetSiblingIndex(info.Value);
            }

            //children重新设置anchoredPosition;
            for (int index = 0; index < transform.childCount; index++)
            {
                Transform child = transform.GetChild(index);

                RectTransform childRectTrans = child.GetComponent<RectTransform>();
                if (childsAnchoredPosition.ContainsKey(child))
                {
                    childRectTrans.anchoredPosition = childsAnchoredPosition[child];
                }
                else if (child.GetSiblingIndex() <= minAmount)
                {
                    childsAnchoredPosition.Add(child, childRectTrans.anchoredPosition);
                    childsSiblingIndex.Add(child, child.GetSiblingIndex());
                }
                else
                {
                    Debug.LogError("childsAnchoredPosition no contain " + child.name);
                }
            }
        }

        //获取所有child;
        for (int index = 0; index < transform.childCount; index++)
        {
            Transform trans = transform.GetChild(index);
            trans.gameObject.SetActive(true);

            children.Add(transform.GetChild(index).GetComponent<RectTransform>());

            //初始化前面几个;
            UpdateChildrenCallback(children.Count - 1, transform.GetChild(index));
        }

        if (initCompleteCallback != null)
        {
            initCompleteCallback.Invoke();
        }


        startPosition = rectTransform.anchoredPosition;

        realIndex = children.Count - 1;

        //Debug.Log( scrollRect.transform.TransformPoint(Vector3.zero));

        // Debug.Log(transform.TransformPoint(children[0].localPosition));

        hasInit = true;

        //如果需要显示的个数小于设定的个数;
        for (int index = 0; index < minAmount; index++)
        {
            children[index].gameObject.SetActive(index < amount);
        }

        if (gridLayoutGroup.constraint == GridLayoutGroup.Constraint.FixedColumnCount)
        {
            //如果小了一行,则需要把GridLayout的高度减去一行的高度;
            int row = (minAmount - amount) / gridLayoutGroup.constraintCount;
            if (row > 0)
            {
                rectTransform.sizeDelta -= new Vector2(0, (gridLayoutGroup.cellSize.y + gridLayoutGroup.spacing.y) * row);
            }
        }
        else
        {
            //如果小了一列,则需要把GridLayout的宽度减去一列的宽度;
            int column = (minAmount - amount) / gridLayoutGroup.constraintCount;
            if (column > 0)
            {
                rectTransform.sizeDelta -= new Vector2((gridLayoutGroup.cellSize.x + gridLayoutGroup.spacing.x) * column, 0);
            }
        }
    }

    // Update is called once per frame
    void Update()
    {

    }


    void ScrollCallback(Vector2 data)
    {
        UpdateChildren();
    }

    void UpdateChildren()
    {
        if (transform.childCount < minAmount)
        {
            return;
        }

        float itemHeight = children[children.Count - 1].rect.height * 0.5f;
        Vector2 currentPos = rectTransform.anchoredPosition;

        if (gridLayoutGroup.constraint == GridLayoutGroup.Constraint.FixedColumnCount)
        {
            float offsetY = currentPos.y - startPosition.y;

            if (offsetY > 0)
            {
                //向上拉,向下扩展;
                {
                    if (realIndex >= amount - 1)
                    {
                        startPosition = currentPos;
                        return;
                    }

                    float scrollRectUp = scrollRect.transform.TransformPoint(Vector3.zero).y;

                    Vector3 childBottomLeft = new Vector3(children[0].anchoredPosition.x, children[0].anchoredPosition.y - gridLayoutGroup.cellSize.y, 0f);
                    float childBottom = transform.TransformPoint(childBottomLeft).y;
                    //Debug.Log(" childBottom " + childBottom + " scrollRectUp " + scrollRectUp);
                    if (childBottom >= scrollRectUp)
                    {
                        //Debug.Log("childBottom >= scrollRectUp");

                        //移动到底部;
                        for (int index = 0; index < gridLayoutGroup.constraintCount; index++)
                        {
                            children[index].SetAsLastSibling();

                            children[index].anchoredPosition = new Vector2(children[index].anchoredPosition.x, children[children.Count - 1].anchoredPosition.y - gridLayoutGroup.cellSize.y - gridLayoutGroup.spacing.y);

                            realIndex++;

                            if (realIndex > amount - 1)
                            {
                                children[index].gameObject.SetActive(false);
                            }
                            else
                            {
                                UpdateChildrenCallback(realIndex, children[index]);
                            }
                        }

                        //GridLayoutGroup 底部加长;
                        rectTransform.sizeDelta += new Vector2(0, gridLayoutGroup.cellSize.y + gridLayoutGroup.spacing.y);

                        //更新child;
                        for (int index = 0; index < children.Count; index++)
                        {
                            children[index] = transform.GetChild(index).GetComponent<RectTransform>();
                        }
                    }
                }
            }
            else
            {
                //Debug.Log("Drag Down");
                //向下拉,下面收缩;
                if (realIndex + 1 <= children.Count)
                {
                    startPosition = currentPos;
                    return;
                }
                RectTransform scrollRectTransform = scrollRect.GetComponent<RectTransform>();
                Vector3 scrollRectAnchorBottom = new Vector3(0, -scrollRectTransform.rect.height - gridLayoutGroup.spacing.y, 0f);
                float scrollRectBottom = scrollRect.transform.TransformPoint(scrollRectAnchorBottom).y;


                Vector3 childUpLeft = new Vector3(children[children.Count - 1].anchoredPosition.x, children[children.Count - 1].anchoredPosition.y + itemHeight, 0f);

                float childUp = transform.TransformPoint(childUpLeft).y;
                //Debug.Log("name " + transform.name + " childUp " + childUp + " scrollRectBottom " + scrollRectBottom);
                if (childUp < scrollRectBottom)
                {
                    //Debug.Log("childUp < scrollRectBottom");

                    //把底部的一行 移动到顶部



                    for (int index = 0; index < gridLayoutGroup.constraintCount; index++)
                    {
                        children[children.Count - 1 - index].SetAsFirstSibling();

                        children[children.Count - 1 - index].anchoredPosition = new Vector2(children[children.Count - 1 - index].anchoredPosition.x, children[0].anchoredPosition.y + gridLayoutGroup.cellSize.y + gridLayoutGroup.spacing.y);

                        children[children.Count - 1 - index].gameObject.SetActive(true);

                        UpdateChildrenCallback(realIndex - children.Count - index, children[children.Count - 1 - index]);
                    }

                    realIndex -= gridLayoutGroup.constraintCount;

                    //GridLayoutGroup 底部缩短;
                    rectTransform.sizeDelta -= new Vector2(0, gridLayoutGroup.cellSize.y + gridLayoutGroup.spacing.y);

                    //更新child;
                    for (int index = 0; index < children.Count; index++)
                    {
                        children[index] = transform.GetChild(index).GetComponent<RectTransform>();
                    }
                }
            }
        }
        else
        {
            float offsetX = currentPos.x - startPosition.x;

            if (offsetX < 0)
            {
                //向左拉,向右扩展;
                {
                    if (realIndex >= amount - 1)
                    {
                        startPosition = currentPos;
                        return;
                    }

                    float scrollRectLeft = scrollRect.transform.TransformPoint(Vector3.zero).x;

                    Vector3 childBottomRight = new Vector3(children[0].anchoredPosition.x + gridLayoutGroup.cellSize.x, children[0].anchoredPosition.y, 0f);
                    float childRight = transform.TransformPoint(childBottomRight).x;

                    // Debug.LogError("childRight=" + childRight);

                    if (childRight <= scrollRectLeft)
                    {
                        //Debug.Log("childRight <= scrollRectLeft");

                        //移动到右边;
                        for (int index = 0; index < gridLayoutGroup.constraintCount; index++)
                        {
                            children[index].SetAsLastSibling();

                            children[index].anchoredPosition = new Vector2(children[children.Count - 1].anchoredPosition.x + gridLayoutGroup.cellSize.x + gridLayoutGroup.spacing.x, children[index].anchoredPosition.y);

                            realIndex++;

                            if (realIndex > amount - 1)
                            {
                                children[index].gameObject.SetActive(false);
                            }
                            else
                            {
                                UpdateChildrenCallback(realIndex, children[index]);
                            }
                        }

                        //GridLayoutGroup 右侧加长;
                        rectTransform.sizeDelta += new Vector2(gridLayoutGroup.cellSize.x + gridLayoutGroup.spacing.x, 0);

                        //更新child;
                        for (int index = 0; index < children.Count; index++)
                        {
                            children[index] = transform.GetChild(index).GetComponent<RectTransform>();
                        }
                    }
                }
            }
            else
            {
                //Debug.Log("Drag Down");
                //向右拉,右边收缩;
                if (realIndex + 1 <= children.Count)
                {
                    startPosition = currentPos;
                    return;
                }
                RectTransform scrollRectTransform = scrollRect.GetComponent<RectTransform>();
                Vector3 scrollRectAnchorRight = new Vector3(scrollRectTransform.rect.width + gridLayoutGroup.spacing.x, 0, 0f);
                float scrollRectRight = scrollRect.transform.TransformPoint(scrollRectAnchorRight).x;

                Vector3 childUpLeft = new Vector3(children[children.Count - 1].anchoredPosition.x, children[children.Count - 1].anchoredPosition.y, 0f);

                float childLeft = transform.TransformPoint(childUpLeft).x;

                if (childLeft >= scrollRectRight)
                {
                    //Debug.LogError("childLeft > scrollRectRight");

                    //把右边的一行 移动到左边;
                    for (int index = 0; index < gridLayoutGroup.constraintCount; index++)
                    {
                        children[children.Count - 1 - index].SetAsFirstSibling();

                        children[children.Count - 1 - index].anchoredPosition = new Vector2(children[0].anchoredPosition.x - gridLayoutGroup.cellSize.x - gridLayoutGroup.spacing.x, children[children.Count - 1 - index].anchoredPosition.y);

                        children[children.Count - 1 - index].gameObject.SetActive(true);

                        UpdateChildrenCallback(realIndex - children.Count - index, children[children.Count - 1 - index]);
                    }



                    //GridLayoutGroup 右侧缩短;
                    rectTransform.sizeDelta -= new Vector2(gridLayoutGroup.cellSize.x + gridLayoutGroup.spacing.x, 0);

                    //更新child;
                    for (int index = 0; index < children.Count; index++)
                    {
                        children[index] = transform.GetChild(index).GetComponent<RectTransform>();
                    }

                    realIndex -= gridLayoutGroup.constraintCount;
                }
            }
        }

        startPosition = currentPos;
    }

    void UpdateChildrenCallback(int index, Transform trans)
    {
        if (updateChildrenCallback != null)
        {
            updateChildrenCallback(index, trans);
        }
    }

    /// <summary>
    /// 刷新并且回到顶端
    /// </summary>
    public void Refresh()
    {
        scrollRect.StopMovement();
        scrollRect.content.localPosition = Vector3.zero;
        StartCoroutine(InitChildren());
    }


    /// <summary>
    /// 设置总个数;
    /// </summary>
    /// <param name="count"></param>
    public void SetAmount(int count)
    {
        amount = count;
        Debug.Log("SetAmount " + amount);
    }

    /// <summary>
    /// 初始化孩子数据
    /// </summary>
    public void Init()
    {
        StartCoroutine(WaitThenExcu());
    }

    IEnumerator WaitThenExcu()
    {
        for (int i = 0; i < transform.childCount; i++)
        {
            transform.GetChild(i).gameObject.SetActive(true);
        }
        contentSizeFitter.enabled = true;
        gridLayoutGroup.enabled = true;
        yield return 0;
        StartCoroutine(InitChildren());
    }

    /// <summary>
    /// 创建预置
    /// </summary>
    /// <param name="_item">预置</param>
    /// <param name="_parent">父节点</param>
    /// <param name="_need">需要的个数</param>
    /// <param name="cb">对象池 创建的对象存在对象池中</param>
    public void CreateItem(GameObject _item, Transform _parent, int _need, CacheBase cb)
    {
        int tmp = amount > _need ? _need : amount;
        int need = tmp - cb.Pool.Count;
        minAmount = tmp;

        Debug.Log("CreateItem " + need + " tmp " + tmp + " pool.Count " + cb.Pool.Count);
        for (int i = 0; i < need; i++)
        {
            GameObject go = GameObject.Instantiate(_item) as GameObject;
            go.name = "item";
            go.transform.SetParent(_parent);
            go.transform.localScale = Vector3.one;
            //go.GetComponent<RectTransform>().sizeDelta = Vector3.zero;
            go.gameObject.SetActive(true);
            cb.Add(go);
            if (itemCallback != null)
            {
                itemCallback(go);
            }
        }
    }
}

最后附上对象池,仅供参考.

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


//游戏对象缓存
public class CachePoolFactory
{
    private static Dictionary<string, CacheBase> caches = new Dictionary<string, CacheBase>();
    public static CacheBase GetPool(string key)
    {
        if (!caches.ContainsKey(key))
            caches.Add(key, new CacheBase());

        return caches[key];
    }

    public static void Dispose()
    {
        var enumrator = caches.GetEnumerator();
        while (enumrator.MoveNext())
        {
            enumrator.Current.Value.Clear();
        }
    }
}

public class CacheBase
{
    public List<GameObject> Pool;

    public CacheBase()
    {
        Init();
    }

    public void Init()
    {
        Pool = new List<GameObject>();
    }

    public virtual void Add(GameObject go)
    {
        Pool.Add(go);
    }

    public virtual void Remove(GameObject go)
    {
        Pool.Remove(go);
    }

    public virtual void RemoveLast()
    {
        Texture2D.Destroy(Pool[Pool.Count - 1]);
        Pool.RemoveAt(Pool.Count - 1);
        Debug.Log("RemoveLast " + Pool.Count);
    }

    public virtual void Clear()
    {
        for (int i = Pool.Count - 1; i >= 0; i--)
        {
            if (Pool[i] != null)
                Texture2D.Destroy(Pool[i]);
            Pool.RemoveAt(i);
        }
    }

}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,397评论 25 707
  • This article is a record of my journey to learn Game Deve...
    蔡子聪阅读 3,750评论 0 9
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,016评论 4 62
  • 2017年 5月22日 星期一 雨天 大家好,我是236号星宝宝,我正在参加小牛妈妈日记星球第五期蜕变之旅,这是我...
    新加坡秀英阅读 106评论 0 0
  • 有这么个需求,获取一堆ip,想排个序。发现直接使用sorted排序得不到想要的结果,因为sorted默认是按照字符...
    _简_述_阅读 1,577评论 0 1