Question by
XLives · Sep 26, 2018 at 05:41 PM ·
scrollviewrecttransformvisibility
Determine if a panel with rectTransform is visible inside scroll view
How to kown if a panel is visible inside a scrollview? I have this script but it only works if the scroll view has de dimensions of the screen. I need a script "size independent" in a canvas screen space overlay.
in this example the script is attached to a panel inside the scrollview.
CheckIsVisible() executes when user moves the scroll and prints true or false depending on whether the panel is visible or not
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RectVisivility : MonoBehaviour
{
private ScrollRect myScroll;
private RectTransform myRect;
private Vector2 lastValue;
private RectTransform viewPortRect;
private Rect rectScroll;
private void OnEnable()
{
myRect = GetComponent<RectTransform>();
myScroll = GetComponentInParent<ScrollRect>();
viewPortRect = myScroll.GetComponent<RectTransform>();
rectScroll = RectTransformToScreenSpace(viewPortRect);
myScroll.onValueChanged.AddListener(OnScroll);
Debug.Log(rectScroll.height + " " + Screen.height);
}
private void OnDisable()
{
myScroll.onValueChanged.RemoveListener(OnScroll);
}
void OnScroll(Vector2 value)
{
CheckIsVisible();
}
private void CheckIsVisible()
{
Rect rect = RectTransformToScreenSpace(myRect);
Debug.Log(rect + " " + rectScroll + " " + rectScroll.Overlaps(rect));
}
public Rect RectTransformToScreenSpace(RectTransform transform)
{
Vector2 size = Vector2.Scale(transform.rect.size, transform.lossyScale);
Rect rect = new Rect(transform.position.x, Screen.height - transform.position.y, size.x, size.y);
rect.x -= (transform.pivot.x * size.x);
rect.y -= ((1.0f - transform.pivot.y) * size.y);
return rect;
}
}
Comment