Trying to draw GUI.Label() at object position

Hey, I have a quick question

I'm trying to draw a GUI.Label() at an gameobjects position. I got the function I need, and I tested it out, and it works, but its not quite right. I'm using the standard (I believe) FPC for the character. The Script for the label is as follows:

    var bins:GameObject[] = GameObject.FindGameObjectsWithTag("bin");
for (var bin:GameObject in bins)
{
        /*find bin coordinates and make label*/
        var p = Camera.main.WorldToScreenPoint(bin.transform.position);
        GUI.Label(Rect(p.x,p.y,200,30),bin.name);
}

what happens is, as the camera moves, the x position of the label is fine, and where its suppose to be. however, the Y coordinate seems to go way off, just like if a pivot point for an object is off when you're rotating it. Any idea what I'm doing wrong? Thanks.

1 Like

So in case that anyone falls in here, here’s a solution with code:

  private string text;

  void OnGUI() {
    var position = Camera.main.WorldToScreenPoint(gameObject.transform.position);
    var textSize = GUI.skin.label.CalcSize(new GUIContent(text));
    GUI.Label(new Rect(position.x, Screen.height - position.y, textSize.x, textSize.y), text);
  }

Ok I figured out what was going on. Apparently, the WorldToScreenPoint and WorldToViewportPoint functions return an integer(or float respectively) starting from 0,0 at the BOTTOM LEFT of the screen. Because of this, the y-value that I was getting was basicly flipped. So to solve the problem, I just had to subtract the value we got by the height to get the real coordinates. hopefully this helps any one else that was wondering :)

Just a guess, but try using p.z where you have p.y right now.

Did you try setting a custom gui style to the label and playing with the alignment of the text? That sometimes throws me off.

Here’s what I’m using. It’s not perfect but close enough for debugging. Any idea on how it could be fixed?

    void OnGUI()
    {
        var point = Camera.main.WorldToScreenPoint(transform.position);
        GUI.Label(new Rect(point.x, Screen.currentResolution.height - point.y - 200, 200, 200), name);
    }