WorldToScreenPoint and ScreenToWorldPoint

Hi. So I’m trying to dynamically put buttons in locations depending on the screen size, and I’m running into a lot of trouble. Here’s a little bit of code:

Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position);
screenPos = new Vector3((int)(x * Screen.width), (int)(y * Screen.height), screenPos.z);
transform.position = Camera.main.ScreenToWorldPoint(screenPos);

x and y are percentage values. I’ve been using things like x = .1 and y = .9 to get it to the top left corner, but it hasn’t been working at all. When I print the values, I get extremely weird numbers. Like for example, I’ve tried this just to see what would print out:

transform.position = Camera.main.ScreenToWorldPoint(new Vector3(0,0 0));
print("Screen Position: " + Camera.main.WorldToScreenPoint(transform.position));

And what I got was:

I also tried doing Screen.height - y * Screen.height after Googling a lot, because apparently the Y value is opposite?

Anyways, what’s going on here?

If I understand right, your transform is transform of Button? Then you’re doing it wrong:

World point isn’t pixel-wise, it’s point in world units where you render things. It can be (100500, 100500) or (-100500,-100500). It’s point in world and you might not see it.
Screen point is pixel point on screen. It can’t be higher than resolution(Screen.width-1 and Screen.height-1) or lower than (0,0).
Camera renders world space into screen space, then draws overlay (UI, buttons, etc) on screen space.

You try to place button in world point while it’s binded to on-screen coordinate and should be screen point from the beginning… Unless you didn’t mention something.

Y being opposite is common as Windows uses Y=0 as top of screen and Y=height as bottom of screen. Shouldn’t be so in Unity as it uses bottom left coordinate as its (0,0) point… I think you’ve mixed up coordinates a lot already so it might’ve accidentally inverted Y.

P.S. why not use Unity.UI and its anchors? RectTransform is powerful tool for that that works without any changes runtime.

1 Like

OK. Didn’t know there was two different spaces that rendered objects. New to Unity so I’ll look up some stuff about anchors and post back if I need some more help. Thanks a lot, man. I think you got me pointed in the right direction.

EDIT: Just fixed it. Took me 2 minutes with anchors. -_-