完整代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CreateScro : MonoBehaviour
{
public enum Direction
{
Horizontal,
Vertical
}
public RectTransform prefab;
public ScrollRect scroll;
public RectOffset padding;
public float spacing;
public Direction dir = Direction.Horizontal;
public int num;
public RectTransform content;
public RectTransform mask;
public Dictionary<Rect, int> dic = new Dictionary<Rect, int>();
public Dictionary<Rect, GameObject> showdic = new Dictionary<Rect, GameObject>();
Queue<GameObject> que = new Queue<GameObject>();
// Start is called before the first frame update
void Start()
{
if (dir==Direction.Horizontal)
{
float w = padding.left + prefab.rect.width * num + spacing * (num - 1) + padding.right;
float h = padding.top + prefab.rect.height + padding.bottom;
content.sizeDelta = new Vector2(w, h);
for (int i = 0; i < num; i++)
{
dic.Add(new Rect(new Vector2(padding.left+(prefab.rect.width+spacing)*i+prefab.rect.width/2-w/2,0),prefab.sizeDelta),i);
}
}
else
{
float w = padding.left + prefab.rect.width + padding.right;
float h = padding.top + prefab.rect.height * num + spacing * (num - 1) + padding.bottom;
content.sizeDelta = new Vector2(w, h);
for (int i = 0; i < num; i++)
{
dic.Add(new Rect(new Vector2(0,padding.top+(prefab.rect.height+spacing)*i+prefab.rect.height/2-h/2),prefab.sizeDelta),i);
}
}
OnSlide();
}
public void OnSlide()
{
Rect rect = new Rect(-content.anchoredPosition, new Vector2(mask.rect.width, mask.rect.height));
Debug.Log("mask:"+rect);
//找到需要显示的
Dictionary<Rect, int> show = new Dictionary<Rect, int>();
foreach (var item in dic)
{
if (IsOverlap(rect,item.Key))
{
show.Add(item.Key,item.Value);
}
}
//找创建好单不需要显示的
List<Rect> rem = new List<Rect>();
foreach (var item in showdic)
{
if (!IsOverlap(rect,item.Key))
{
que.Enqueue(item.Value);
rem.Add(item.Key);
}
}
foreach (var item in rem)
{
showdic.Remove(item);
}
//创建需要显示的
foreach (var item in show)
{
if (!showdic.ContainsKey(item.Key))
{
GameObject obj;
Debug.Log(que.Count);
if (que.Count>0)
{
obj = que.Dequeue();
}
else
{
obj = Instantiate(prefab.gameObject, content);
}
obj.GetComponent<RectTransform>().anchoredPosition = item.Key.position;
obj.transform.GetChild(0).GetComponent<Image>().sprite =
Resources.Load<Sprite>("Image/image_" + item.Value);
showdic.Add(item.Key,obj);
}
}
}
private bool IsOverlap(Rect rect1, Rect rect2)
{
float r1lefe = rect1.x - rect1.width / 2;
float r1right = rect1.x + rect1.width / 2;
float r1down = rect1.y - rect1.height / 2;
float r1up = rect1.y + rect1.height / 2;
float r2lefe = rect2.x - rect2.width / 2;
float r2right = rect2.x + rect2.width / 2;
float r2down = rect2.y - rect2.height / 2;
float r2up = rect2.y + rect2.height / 2;
if (r1lefe<r2right&&r2lefe<r1right&&r1down<r2up&&r2down<r1up)
{
return true;
}
return false;
}
}