using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace CreatGame.UI { /// /// item提供者 /// public delegate string LoopListItemProvider(int index); /// /// item渲染函数 /// public delegate void LoopListItemRenderer(GameObject item,int index); [RequireComponent(typeof(UnityEngine.UI.LoopScrollRect))] [DisallowMultipleComponent] public class UILoopList : MonoBehaviour, LoopScrollPrefabSource, LoopScrollDataSource { /// /// /// public LoopListItemRenderer ListItemRenderer; /// /// /// private Stack itemPool = new Stack(); /// /// 预制件 /// public GameObject itemPrefab; public GameObject GetObject(int index) { if (itemPool.Count == 0) { return Instantiate(itemPrefab); } Transform candidate = itemPool.Pop(); candidate.gameObject.SetActive(true); return candidate.gameObject; } public void ReturnObject(Transform trans) { trans.gameObject.SetActive(false); trans.SetParent(transform, false); itemPool.Push(trans);; } public void ProvideData(Transform transform, int idx) { if (ListItemRenderer == null) { Debug.LogError("ListItemRenderer is null"); return; } ListItemRenderer(transform.gameObject, idx); } /// /// /// public LoopScrollRect ScrollRect { get; private set; } private void Awake() { ScrollRect = GetComponent(); ScrollRect.prefabSource = this; ScrollRect.dataSource = this; } public int ItemCount { get => ScrollRect.totalCount; set { ScrollRect.totalCount = value; ScrollRect.RefreshCells(); } } public void ScrollToItem(int index) { ScrollRect?.ScrollToCell(index - 1,100.0f); } } }