I have created world space canvas for my dialogue popups similar to the one in Ruby-2d tutorial World Interactions - Dialog Raycast - Unity Learn
(point 3 describes the steps).
Now I want to spawn those dynamically trough code. Finding correct point to place the dialogue wasn’t that hard - I got my main camera object and used WorldToScreenPoint on the place I want the UI to be spawned, and it all works fine.
Next thing I want to confine the UI to be sure it is visible on the screen. So I’m using Mathf.Clamp to make sure the UI is between 0 and Screen.Width/Height. This is almost there…
The problem I have is that I really have to confine the UI to be between 0 + halfOfDialogueUIWidth and Screen.Width - halfOFDialogueUIWidth, similar for height. To do that I need to know my components size in pixels in screen space. When I take screenshot of the game in 1080p it has resolution of 1000x280px. So I’m trying to find a way to calculate that so it actually works regardless of the resolution, instead of being hardcoded.
I’ve tried adding the spriterenderer to one of components, and getting it’s bounds - but the pixels were totally off. I tried using various parameters found in transform.rect but none of them ended up giving me proper size. I for example tried taking min and max point and getting the distance between x and y, but that came out to tens of thousands. I have a suspicion that is actually proper approach, but I might be missing when trying to convert it to proper pixel size?
As additional information I’m using cinemachine camera in Orthographic mode. All my math for placing the ui works properly when I hardcode the size of 1000x280, so all I need to find out is how to get that size from code.