- Home /
Rect.Contains and Rect.Overlap always return true
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class CheckOverlap: MonoBehaviour
{
RectTransform rectTransform;
public RectTransform otherRect;
void Start ()
{
rectTransform = GetComponent<RectTransform> ();
}
void Update ()
{
if (otherRect.rect.Contains(rectTransform.rect.center))
{
print ("Contains");
}
if (otherRect.rect.Overlaps(rectTransform.rect))
{
print ("Overlaps");
}
}
}
..
..
This is the only code, and the two Rects I'm comparing are newly generated UI Images. One has the script and sets the other as "otherRect".
It just spams "True" regardless of where the Rects are from scene start.
Can you print the values of otherRect.rect
and rectTransform.rect
Answer by lassade · Jan 23, 2018 at 03:12 AM
Like I was suspecting the RectTransform.rect
is in local space this means that the center will be always Vector3.zero. Try this fucntion:
Rect GetWorldSapceRect(RectTransform rt)
{
var r = rt.rect;
r.center = rt.TransformPoint(r.center);
r.size = rt.TransformVector(r.size);
return r;
}
Edit: This code does not allow for any kind of rotation between the rectangles since it's an axis aligned structure. To support that kind of thing you may want to use Physics2D to avoid any crazy maths.
Using Colliders2D inside your UI can be tricky but is doable.
Thanks for the reply. I didn't even think to check for that as it seems incredibly stupid that there would be public access to an object's Rect properties when they will always return zero.
Checking that confirms it, so I'll be using your solution.
You my friend are legend, you have no idea how much i want to thank you.
Your answer
Follow this Question
Related Questions
Check if rotated UI are overlapping based on Rotation.Z 0 Answers
Changing the size of the RectTransform's rect 0 Answers
RectTransform returning incorrect rect bounds 0 Answers
Horizontal Layout Group making a Scroll Rect's Content rect width to be negative 1 Answer
ScrollRect - Scroll outside the rect!? 0 Answers