使用UGUI ScrollView 排列不规则内容元素实现滑动效果

来源:互联网 发布:java import include 编辑:程序博客网 时间:2024/05/16 11:52

在开发Unity项目中有时会遇到滑动视图,这个一般实现方式都是使用UGUI组件ScrollView实现,搭配GridLayoutGroup,以及ContentSizeFitter实现,但是当项目中需要使用不规则内容元素动态载入的时候,GridLayoutGruop就变得不太适用。。。正好在项目中,遇到这个问题,我把我的做法分享一下,也算给自己记一个笔迹。
1,我的实现方式是,使用VerticalLayoutGroup,以及ContentSizeFitter,以及自己写的一个类似ContentSizeFitter代码实现。
实现效果简要说明:
这里写图片描述

具体实现步骤图示
步骤一:
这里写图片描述
步骤二:
这里写图片描述
步骤三:
这里写图片描述
步骤四:
这里写图片描述
步骤五:
这里写图片描述
步骤六:计算ScrollView显示区高度

using System.Collections;using UnityEngine;public class ListUIMng : MonoBehaviour {    public GameObject prefab;    public Transform content;    // Use this for initialization    void Start()    {        SizeInit();    }    // Update is called once per frame    void Update () {    }    private void OnGUI()    {        if (GUI.Button(new Rect(20,100,100,50),"添加道具"))        {            GameObject tool = GameObject.Instantiate(prefab);            tool.transform.parent = content.GetChild(1);            StartCoroutine(SetHight());        }        if (GUI.Button(new Rect(20, 300, 100, 50), "添加应用场景"))        {            GameObject scence = GameObject.Instantiate(prefab);            scence.transform.parent = content.GetChild(content.childCount - 1);            StartCoroutine(SetHight());        }    }    public void SizeInit()    {      StartCoroutine(SetHight());    }    IEnumerator SetHight()    {        yield return new WaitForSeconds(0.1f);        //采用高度累加的方式,避免动态加入元素,最后元素位置不刷新问题(通过第一个元素和最后元素计算,刷新延迟会出问题)        float hight = 0;        for (int i = 0; i < content.childCount; i++)        {            hight += content.GetChild(i).GetComponent<RectTransform>().sizeDelta.y;        }        Debug.Log("======hight==" + hight);        RectTransform rect = content.GetComponent<RectTransform>();        rect.sizeDelta = new Vector2(rect.sizeDelta.x, hight);    }}