This code snippet OnGUI() will show the string “Hello” on top of the transform targeted by the script [C#]:
screenPos = Camera.main.WorldToScreenPoint(transform.position);
GUI.Label(new Rect(screenPos.x, screenPos.y, screenPos.x+20, screenPos.y+30), "Hello!");
The code works but the string is located high up the screen, too far away from the object invoking the script. How do I lower the Label so that it’s closer to the object calling it?
First, the size of the rect of that label depend of the position of the transform, but you don’t need that. Imagine the transform is on the bottom right corner, the Rect will be the size of the screen. Use a constant width and height.
To make sure the label is on top of the transform, first use a style with LowerCenter alignement. Then, draw it so the bottom center of the rect is on top of the transform :
GUI.Label(new Rect(screenPos.x - 100, screenPos.y + 100, 200, 100), "Hello!", myStyle);