placing gui text

Hi there guys

Is it possible to place gui text at the x and y position of an game object and if so, can someone please help me with an example? I have a 2d application and I need this since my text must always be in the top middle of a block object that might change position at times.

Thanks

anyone that can help?

Watch out though, this returns the screen position with cords starting at the bottom right. And GUI rects start at the top left. So simply inverting it will work;

function OnGUI(){
      var screenPos : Vector3 = camera.WorldToScreenPoint (target.position);
      GUI.Label(Rect(screenPos.x,Screen.height - screenPos.y,100,100),"Hello");
}

That should do it.

If you weren’t answered in the above (because you are using GUIText not GUILabel), then there are two possibilities…

If the object you are placing things alongside is a GUITexture then use pixelInset and pixelOffset if it’s a 3D object then something like posted above (untested code but hopefully enough to give you the idea, this will roughly stick it in the middle of the object if your anchor is middle centre):

function WhereeverYouNeedToUpdateThis()
      var screenPos : Vector3 = camera.WorldToScreenPoint (target.position);
      guiText.pixelOffset.x = screenPos.x;
      guiText.pixelOffset.y = screenPos.y ;
}

To get it at the top you will have to work out the top point of the object, how to do this will depend on what your target object does and it’s shape. So I’ll leave that for now :slight_smile:

Thanks guys, I will try this and give some feedback!

King’s solution is solid except you definitely don’t want to be doing that calculation in OnGUI(). OnGUI() is called multiple times per frame, and doing any sort of calculations like that in it can cause some serious performance issues. You’re better off doing something like:

private var screenPos : Vector3;

function Update(){
    screenPos : Vector3 = camera.WorldToScreenPoint(target.position);
}

function OnGUI(){
      GUI.Label(Rect(screenPos.x,Screen.height - screenPos.y,100,100),"Hello");
}

Ok, thanks guys, camera.WorldToScreenPoint works perfectly. What I did was to add an empty game object and used that as the point where the label must be created.