GUI Window on GameObject location?

How can i know the X,Y for the window that i want to PopUp so it will always show up on the same position of the GameObject?

I currently have this but it wont work:

        Vector3 t = unitToPopup.transform.position;
		GUI.Window(0, new Rect(,, 120, 50), CreateUnitWindow, "My Window");

You could use this:

  Vector3 pos = Camera.main.WorldToScreenPoint(unitToPopup.transform.position);
  GUI.Window(0, new Rect(pos.x, pos.y, 120, 50), CreateUnitWindow, "My Window");

You only can use the camera variable when the object to which this script is assigned is a camera or have a camera component (added, not childed!).


The difference from your code is the use of Camera.main instead of camera, but this will not make any difference if this script is attached to the camera.

Doing a second reading, I suppose your problem is caused by the different Y orientations between GUI and screen points: GUI Y origin is at the screen top, while screen coordinates start at the bottom. Another problem: the window top-left will be aligned to the object’s center, what may not give a good result - maybe you should add some offset to make it appear above the object. Reversing the Y coordinate and adding an offset could be done this way:

// define an offset value to keep the window top above the object
public float offset = 60; //offset in pixels
  Vector3 pos = Camera.main.WorldToScreenPoint(unitToPopup.transform.position);
  // make Y coordinate run from top, and add some offset to keep it above the object
  Rect wRect = new Rect(pos.x, Screen.height-(pos.y+offset), 120, 50);
  GUI.Window(0, wRect, CreateUnitWindow, "My Window");

NOTE: WorldToScreenPoint may return a valid screen coordinate even when the object is behind the camera; if you have this problem, check if renderer.isVisible is true before rendering the window (this actually tells if the object is inside the view frustum of any camera):

  if (unitToPopup.renderer.isVisible){
    Vector3 pos = Camera.main.WorldToScreenPoint(unitToPopup.transform.position);
    GUI.Window(0, wRect, CreateUnitWindow, "My Window");