Unity 无限滚动条 自己写的记录一下
content 需要和 Scroll View 宽高一致 其他情况自行修改
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;public class mScrollView : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
{public delegate void OnIndexChange(int index);public OnIndexChange onIndexChange;public GameObject Item;public int ItemCount;public float spacing;private ScrollRect scrollRect;private List<Vector2> ItemPos = new List<Vector2>();private int Index = 0;private bool move = false;private RectTransform[] goArray = new RectTransform[3];private float time = 1f;private float inputy = 0;private Vector2 itemSizData;private Color[] colors = new Color[3] { Color.red, Color.yellow, Color.green };void Start(){scrollRect = GetComponent<ScrollRect>();itemSizData = ((RectTransform)Item.transform).sizeDelta;float y = itemSizData.y * ItemCount + ItemCount * spacing - spacing;scrollRect.content.sizeDelta = new Vector2(0, y);for (int i = 0; i < ItemCount; i++){ItemPos.Add(new Vector2(0, -scrollRect.content.rect.y / 2 - itemSizData.y / 2 - (itemSizData.y + spacing) * i));}for (int i = 0; i < goArray.Length; i++){GameObject go = GameObject.Instantiate(Item, scrollRect.content);go.SetActive(true);go.name = i.ToString();goArray[i] = (RectTransform)go.transform;goArray[i].anchoredPosition = ItemPos[i];go.GetComponent<Image>().color = colors[i];}}public void OnBeginDrag(PointerEventData eventData){inputy = Input.mousePosition.y;}public void OnEndDrag(PointerEventData eventData){if (inputy > Input.mousePosition.y){if (Index > 0){Index--;}}else{if (Index < ItemCount - 1){Index++;}}if (onIndexChange != null) onIndexChange(Index);move = true;Debug.Log(Index);}public void OnDrag(PointerEventData eventData){if (inputy > Input.mousePosition.y){int x = Index;if (x < 2) return;for (int i = 0; i < goArray.Length; i++){if (goArray[i].anchoredPosition.y < ItemPos[Index].y - itemSizData.y / 2){goArray[i].anchoredPosition = ItemPos[x - 2];Debug.Log("向下");break;}}}else if (inputy < Input.mousePosition.y){int x = Index + 1;if (x > ItemCount - 2) return;for (int i = 0; i < goArray.Length; i++){if (goArray[i].anchoredPosition.y > ItemPos[Index].y + itemSizData.y / 2){goArray[i].anchoredPosition = ItemPos[x + 1];Debug.Log("向上");break;}}}}void Update(){if (move){float Toy = (itemSizData.y + spacing) * Index;scrollRect.content.localPosition = Vector2.Lerp(scrollRect.content.localPosition, new Vector2(0, Toy), time);// (scrollRect.verticalNormalizedPosition, Toy, time);if (Vector2.Distance(scrollRect.content.localPosition, new Vector2(0, Toy)) < 1f){move = false;scrollRect.content.localPosition = new Vector2(0, Toy);}}}
}