1
votes

I have certain amount of sprites in my scene. It is a 2D Game. I want to display some text on the sprite each Sprite's GameObject is attached with a Script. In the Script I have the following OnGUI() Method

void OnGUI ()
{
    GUI.contentColor = Color.black;
        Rect label = new Rect ();
        label.x = worldToRect (transform.position).x;
        label.y = worldToRect (transform.position).y;
        label.width = 100;
        label.height = 100;
        GUI.Label (label, number.ToString ());

}
Vector2 worldToRect (Vector3 WorldPosition)
    {
            Vector2 v = Camera.main.WorldToScreenPoint (WorldPosition);
            return GUIUtility.ScreenToGUIPoint (v);
    }

But the position is not quite right. The two white Sprites should display 3 at the centre.I checked their transform in the editor and they align exactly at the centre of the sprite. How do I correct this ? The Two white Sprites should display 3 at the centre.I checked their transform in the editor and they align exactly at the centre of the sprite

1

1 Answers

0
votes

The x and y in the Rect for the label are the top-left position, which is aligned with the center of the GameObjects.

To center them, subtract half the width from x and half the height from y, and make sure the label's style has Alignment set to "Middle Center"