// An highlighted block
using UnityEngine;
public static class RectTransformExtensions
{
public static bool Overlaps(this RectTransform a, RectTransform b)
{
return a.WorldRect().Overlaps(b.WorldRect());
}
public static bool Overlaps(this RectTransform a, RectTransform b, bool allowInverse)
{
return a.WorldRect().Overlaps(b.WorldRect(), allowInverse);
}
public static Rect WorldRect(this RectTransform rectTransform)
{
Vector2 sizeDelta = rectTransform.sizeDelta;
float rectTransformWidth = sizeDelta.x * rectTransform.lossyScale.x;
float rectTransformHeight = sizeDelta.y * rectTransform.lossyScale.y;
Vector3 position = rectTransform.position;
return new Rect(position.x + rectTransformWidth * rectTransform.pivot.x, position.y - rectTransformHeight * rectTransform.pivot.y, rectTransformWidth, rectTransformHeight);
}
}
参考资料:https://stackoverflow.com/questions/42043017/check-if-ui-elements-recttransform-are-overlapping
补加了pivot 不在中间时的错误修改
简单应用示例:
将在scrollrect之外的内容setactive false, 稍微改善下能提升很大的渲染性能,特别是列表内容特别多的时候.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScrollTest : MonoBehaviour {
public List<RectTransform> items;
// Use this for initialization
// Update is called once per frame
void Update () {
for (int i = 0; i < items.Count; i++) {
items [i].gameObject.SetActive (items[i].Overlaps(transform as RectTransform));
}
}
}