It helped position it much closer, but, as you can see, the top right corner of the VisualElement rectangle is not centered on the white dot.
Plus this only worked on the native resolution (scale with screen panel settings). On any other resolution it is completely off on both the x and the y.
I feel like I am possible missing something or is this a bug being worked on?
EDIT: The other direction works perfectly. ScreenToWorld for positioning world objects over VisualElements.
public static Vector3 GetVisualElementWorldPosition(VisualElement ve, float scaleFactor)
{
Vector3 position = Camera.main.ScreenToWorldPoint(ve.worldBound.center * scaleFactor);
position.z = 0;
// Because camera 0,0 is bottom-left and UIToolkit is top-left
position.y *= -1;
return position;
}
The solution to the first problem is that you have to wait until the end of the frame for it to work. Any Unity Developers know if this is a bug and should be reported?
However, this only works on the native resolution. How do you make the code work on all resolutions? Using the scale factor doesn’t seem to help in this instance.
I saw a weird issue couple of days ago, which I did not have time to investigate. I moved to another computer where suddenly my UI panels were completely off. I was desperate after hours of trying to figure out why and then discovered that when I set Windows resolution scale to 100%, the panels were OK. The former computer had 100%, the new station had a larger monitor and 125% scale set in windows, which was throwing the UI system off.
Then I made new panel settings asset and I think it fixed the issue. Again, I did not investigate if this translates to build, or it was just in editor, etc. Anyway I added this to my list of things to look at when debugging weird Unity behavior.
Thanks for the reply. This unfortunately isn’t the issue. It works on the native resolution, but with the scale factor, it doesn’t work on other resolutions because the UI is scaled down. However, in this instance, the scale factor doesn’t seem to be of help.
EDIT: I was able to figure out the second issue with the scale factor. It seems you need to divide instead of multiplying.