UGUI的无限滚动列表

本文介绍了如何在Unity3D中使用UGUI系统实现一个无限滚动的列表效果,通过设置滑动框组件和编写无限滚动脚本来达到目的,并提供了具体的调用方法。
摘要由CSDN通过智能技术生成

 

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

/// <summary>
/// UGUI无限滚动列表
///(by:羽落星辰)
/// </summary>

	public class UGUILoopScrollView : MonoBehaviour
	{
		//方向
		public enum Direction
		{
			Horizontal, //水平
			Vertical,       //垂直
		}

		//暂时默认是1
		[Header("每行/列Cell数量")]
		[SerializeField]
		private int cellConstraintCount = 1;

		[Header("Cell尺寸")]
		[SerializeField]
		private Vector2 CellSize;

		[Header("Cell之间的间距")]
		[SerializeField]
		private Vector2 Spacing;

		[Header("Cell起始位置空余")]
		[SerializeField]
		private float Padding;

		[Header("排列方向")]
		[SerializeField]
		private Direction direction = Direction.Horizontal;

		[Header("Cell物体(必须赋值)")]
		public GameObject mCellObj;

		[Header("滑动框组件(默认是当前物体的父级,其他情况请赋值)")]
		public ScrollRect mScrollView;

		#region CacheData

		//Content组件
		private RectTransform uiTransform;
		//ScrollRect组件
		private RectTransform scrollTransform;
		//Cell列表
		private List<GameObject> list_Cell;
		//list类型的数据结构
		private IList cellDatas;
		//Cell生成的个数
		private int cellCount;
		//Cell数据需要的个数
		private int cellDataCount;
		//当前显示的最小值(列或者行)
		private int minRow;
		//当前显示的最大值(列或者行)
		private int maxRow;
		//cell的回调事件
		private Action<GameObject, int> cellCallBack;

		#endregion

		private void Awake()
		{
			uiTransform = transform.GetComponent<RectTransform>();

			if (transform.parent.GetComponent<ScrollRect>())
				mScrollView = transform.parent.GetComponent<ScrollRect>();

			if (!mScrollView)
			{
				Debug.LogError("ScrollView is null , pleace check it...");
				return;
			}

			scrollTransform = mScrollView.GetComponent<RectTransform>();

			//设置滑动框 滑动方向
			SetScrollRectDirection();

			if (mScrollView)
			{
				mScrollView.onValueChanged.AddListener((value) =>
				{
					RefreshCellPosition();
				});
			}
		}

		/// <summary>
		/// 创建Cell
		/// </summary>
		public void CreateCell()
		{
			//ScrollView的高度(垂直模式)或者宽度(水平模式)
			float scrollViewValue;
			//cell的高度(垂直模式)或者宽度(水平模式)
			float cellValue;

			scrollViewValue = (direction == Direction.Horizontal) ? scrollTransform.sizeDelta.x : scrollTransform.sizeDelta.y;
			cellValue = (direction == Direction.Horizontal) ? CellSize.x : CellSize.y;

			int createCellCount = (Mathf.CeilToInt(scrollViewValue / cellValue) * cellConstraintCount) + 3 * cellConstraintCount;

			list_Cell = new List<GameObject>(createCellCount);
			GameObject cellTemp;
			Vector3 cellPos = Vector3.zero;
			for (int i = 0; i < createCellCount; i += 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值