- Home /
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.
Answer by kennypu · Dec 31, 2010 at 11:15 PM
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 :)
Answer by alejandro__ · Feb 09, 2017 at 07:55 AM
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);
}
Thank you so much! This was exactly what I was looking for!
Answer by DaveA · Dec 31, 2010 at 10:09 PM
Just a guess, but try using p.z where you have p.y right now.
that almost worked. When giving the z value, it doesn't give the weird problem where the positions get thrown off a lot, but now the y value just stays in the same spot on the screen (so if I look up, its in the same spot rather than moving down to match the position of the object).
Answer by PrimeDerektive · Dec 31, 2010 at 10:21 PM
Did you try setting a custom gui style to the label and playing with the alignment of the text? That sometimes throws me off.
Answer by Bryan-Legend · Nov 10, 2013 at 10:50 PM
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);
}
Your answer
Follow this Question
Related Questions
How do I position a GUI Label over an object? 1 Answer
GUI Labels Overlap 2 Answers
Auto positioning GUI Labels? 0 Answers
GUI Label Size and Position Changes With Resolution 2 Answers
GUI.label overlapping text 1 Answer