GUI Text alignment with moving camera in Unity

1.3k views Asked by At

I am making a top-down shooter type of game in Unity. The player can move in the world, but the camera moves with him, so the player is always in the middle of the screen.

I'm trying to display some text in the upper-left corner of the screen, and so I attached a GUItext component to the main camera. The result was quite interesting - the moment the player moves the text darts off the screen.

What the text is supposed to display is controlled by the player, so I added the following snippets of code in my player script:

public GUIText scoreText;
void Update ()
    {
        scoreText.pixelOffset = new Vector2 (300, 300);
    }

void UpdateScore ()
    {
        scoreText.text = "Lives: " + lives;
    }

but that didn't change anything, and the void UpdateScore () didn't work either.

I am rather new to Unity, so this is probably a very simple mistake... but what am I doing terribly wrong?

EDIT: the void UpdateScore () works now that I call from void FixedUpdate ().

EDIT (again): I fixed the problem by making a new Empty Object with nothing in it except the transform (which never moves) and a GUI text component. The problem I have now is that the anchor on the GUI text works very strange - it only works if I put it on the lower-left (whereas I want it on the upper left). Trying to change the anchor moves it somewhere off the screen. Here's my hierarchy: enter image description here

2

There are 2 answers

1
HalpPlz On

Make sure that your GUIText component is attached to its own GameObject that does not move. I would guess that right now it is on your player or the camera.

(When the GameObject the GUIText component is attached to moves, the onscreen position of the displayed text also moves.)

0
HalpPlz On

Are you sure you know what the anchor of a GUIText does? The anchor is which point on the text the offset applies to. E.g. if the anchor is "upper left", and the pixel offset is (300, 300), the upper-left corner of the text will be 300 pixels right of and 300 pixels above the lower-left corner of the screen. If the anchor is "lower left", the lower-left corner of the text will be 300 pixels right of and 300 pixels above the lower-left corner of the screen.

If you want the text to be a certain number of pixels from the upper-left corner of the screen instead of the lower-left corner, change your code to:

scoreText.pixelOffset = new Vector2 (300, Screen.height - 300);

Alternatively, use a Canvas Text element instead of a GUIText. The Anchor of a Text element is its onscreen offset, unlike GUIText.