- Home /
How to set an objects position to the corner of the screen? (Unity 2D)
I am trying to make a HUD for my game and I have a sprite which I want to position in the upper left corner of the screen. The problem is that I want it to be in the corner for every screen resolution. I have tried programming a script but always run into problem.
P.S. I am using C#.
Answer by Aridez · Feb 18, 2014 at 03:10 PM
Add component -> rendering -> gui text/ texture. To create a HUD you should use those, they will be positioned always on a position relative to the camera so you see them on the same position all time.
edit: I had some problems with them while working on 2D, but once you manage to position them inside the camera then is just matter of positioning them where you want.
Answer by robertbu · Feb 18, 2014 at 03:55 PM
Select your Sprite/Texture. Set the pivot for the sprite to the top left. Then you can use Viewport coordinates to place it in the upper left corner. Viewport coordinates go from (0,0) in the lower left to (1,1) in the upper right. So the Viewport coordinate for the upper left is (0,1). In the Start() of a script attached to the sprite put:
transform.position = Camera.main.ViewportToWorldPoint(new Vector3(0,1,0));
Note this like of code assumes an Orthographic camera. If you are using a Perspective camera, you need to set the 'z' of the Vector3() to the distance the sprite is in front of the camera.
I tried this but got an error telling me I can't set the value of a transform.
you have to use the new keyword for the Vector3
transform.position = Camera.main.ViewportToWorldPoint(new Vector3(0,1,0));
Of course the Aridez answer was the best one for your question.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Developing on multiple resolutions 1 Answer
How to wait for Screen.SetResolution to finish? 3 Answers
GUI position and size in different screen resolutions 1 Answer