Is there a simple way to check if a UI element is fully visible on screen ?

I need to do this for two reasons : I want to make a draggable UI window but prevent it from being dragged outside the screen, and I also want to make sure my tooltips don’t overflow from the screen and get cut.

How should I go about doing that ? Is there a way maybe to get the size of a UI element and the size of the Canvas and then compare them ? I feel like I’m missing something here.

Hi,

I use Canvas in Screen Space - Overlay option.
To detect if a RectTransform is visible or out of the screen in my projects I use this solution:

void Update ()
	{
		Vector3[] v = new Vector3[4];
		GetComponent<RectTransform>().GetWorldCorners (v);

		float maxY = Mathf.Max (v [0].y, v [1].y, v [2].y, v [3].y);
		float minY = Mathf.Min (v [0].y, v [1].y, v [2].y, v [3].y);

		//No need to check horizontal visibility: there is only a vertical scroll rect
		//float maxX = Mathf.Max (v [0].x, v [1].x, v [2].x, v [3].x);
		//float minX = Mathf.Min (v [0].x, v [1].x, v [2].x, v [3].x);
		
		if (maxY < 0 || minY > Screen.height) {
			// Do Something that disable UI elements
		} else {
			// Do something that re-enable UI elements
		}
	}

This works for me.
Hope helps.

Are you using uGUI or legacy GUI?

You can get the rect of your UI element and get the four corners then the rect of the screen and do:

if(screenRect.Contains(pos0) )
{
    // Inside
}

My solution is based on the above so credits due. This works with a canvas set as Screen space Camera.

Use this to create a test rect the size of the screen in some Awake fn using the canvas you want to test against:

		Vector3 c1 = mainCanvas.worldCamera.ScreenToWorldPoint(Vector3.zero);
		Vector3 c2 = mainCanvas.worldCamera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height));

		Rect canvasRect = new Rect( c1, new Vector2(c2.x-c1.x, c2.y-c1.y));

Then I did tests on the UI element like this:

		Vector3[] corners = new Vector3[4];

		GetComponent<RectTransform>().GetWorldCorners(corners);

		Rect rec = new Rect(corners[0].x, corners[0].y, corners[2].x-corners[0].x, corners[2].y-corners[0].y);

		if (rec.Overlaps(canvasRect))
...

Well, I have reached some good utility exist in Unity3d, I hope this helps:

RectTransformUtility.RectangleContainsScreenPoint

This makes sense to me (in a way) but I am finding that where the objectCorners are in world coordinates my container rect are different so the test always fails?

This makes sense to me (in a way) but I am finding that where the objectCorners are in world coordinates my container rect are different so the test always fails?

Here is a better way than all of the proposed:

https://forum.unity.com/threads/2-recttransforms-overlapping.515670/