Keeping a gui object in the same screenspace position

Can somebody explain clearly what this block of code does

    Vector3 screenPos;
	void Update ()
    {
         screenPos = camera.WorldToScreenPoint(transform.position);
         transform.position = screenPos;
	}

I am trying to create a gui object that stays in the same position relative to the camera (The camera moves in the x, y axis). I pulled this code from the unity website when looking at what WorldToScreenPoint did. If you think I am going about this the wrong way then tell me otherwise can somebody explain this code clearly.
Thanks and sorry for my ignorance

1 Answer

1

The two lines of code above are nonsense. The first line transforms the world position to a screen position. That is a 3D coordinate is transformed into the pixel position on the screen. I cannot think of a single situation where the second line is correct. You don’t want to assign a screen position directly to a world position.

If you are trying to position things across multiple resolutions, then there are many posts on the issue, and many approaches depending on the needs of your UI. One thing to take a look at is Camera.ViewportToWorldPoint().

There is the GUI class for doing interface work. GUI coordinates are based on pixels, so if the rect you pass to a GUI call remains the same, it will be in the same pixel location relative to the upper left corner of the screen.

Ok thanks I have looked into gui class and I have managed to do what I was trying to achieve thanks for the help