Is there a way to get the world bounds of a UI component with all of its children included?
Okay, I somewhat got it figured out.
It works but isn’t accurate, and requires if you are using the CanvasScaler to get the scale factor.
Currently CanvasScaler.scaleFactor always returns 1.0f if you don’t use Constant Physical Size as the Ui Scale Mode. There is a bug filed about it so hopefully they fix it in the near future.
I am using Scale With Screen Size for the Ui Scale Mode, which allows me to put in a reference resolution. To get around the bug I take the current screen size and divide by the reference resolution to get the current scale factor(current width / reference width).
Bounds CalculateBounds(RectTransform transform, float uiScaleFactor)
{
Bound bounds = new Bounds(transform.position, new Vector3(transform.rect.width, transform.rect.height, 0.0f) * uiScaleFactor);
if (transform.childCount > 0)
{
foreach (RectTransform child in transform)
{
Bounds childBounds = new Bounds(child.position, new Vector3(child.rect.width, child.rect.height, 0.0f) * uiScaleFactor);
bounds.Encapsulate(childBounds);
}
}
return bounds;
}
This is not accurate as I have stated. It doesn’t fully encompass all of the children. It also only works if the pivot is in the center of each object(not hard to fix, I only want it to get all the children right now, then I can set it up to work with any pivot.)
If anyone can help me get this to work it will be greatly appreciated.
I did some more testing trying to figure out why it wasn’t getting the children properly. I was trying to cache the bounds so it doesn’t need to be calculated so often and found that my code wasn’t updating the bounds when it needed to. So it works fine once I got it to do it when it needs to. Now to get it working with arbitrary pivots.
Maybe RectTransformUtility.CalculateRelativeRectTransformBounds can help you to achieve this? ![]()
I’ve tried that and its not scaled to the correct size according to the scale factor of the Ui, plus the position is not correct either, seems to be in local and not world like I need.
Late to the party, but I stumbled across this post with the same problem. I used RectTransform.GetWorldCorners (Unity - Scripting API: RectTransform.GetWorldCorners (unity3d.com)).