- Home /
how do I make a gui element appear in front of an object
I am soon to be reaching a playable phase of my game. I'm wondering how to create an icon that appears right next to or on top of an object. I understand how GUI buttons work and understand how to get the position. I've used ray cast to get the objects coordinates via the GUI coordinates now I need to do it backwards.
Answer by aldonaletto · Aug 29, 2012 at 12:58 AM
You could find the screen coordinates of a 3D world point with Camera.main.WorldToScreenPoint - but be aware that the Y coordinate runs upside down in the GUI system, thus you must invert it.
That's a simple script that shows the object name at offset world units above (script attached to the object):
var width: float = 100; // label width in pixels var height: float = 36; // label height in pixels var offset: float = 2; // offset above object in world units
function OnGUI(){ // calculate the world position for the label: var pos3d = transform.position + Vector3.up * offset; // convert it to screen space: var pos = Camera.main.WorldToScreenPoint(pos3d); // flip the Y coordinate vertically to match GUI space: pos.y = Screen.height - pos.y; // create a rect above pos: var r = Rect(pos.x-width/2, pos.y-height, width, height); // draw it: GUI.Label(r, transform.name); }
I stupidly wrote "var OnGUI" ins$$anonymous$$d of "function OnGUI" - answer fixed now.
Your answer
Follow this Question
Related Questions
Is gameObject present at coordinates (x,y,z)? 1 Answer
GUI co-ordinates bug? 1 Answer
How to position elements on scene 0 Answers
Finding Coordinates of Objects in a List 1 Answer
how to find out the absolute coordinate? 0 Answers