- Home /
Question by
octaviomejiadiaz · Feb 27, 2013 at 06:35 PM ·
cameragameobjectvector3followguibutton
how to reference GameObjects to GUIButton???
i have this code, and every GUIButton have to be reference to each GameObject but still appearing in the same place all the GUIButtons. . how do i put them to follor each GameObject?
code:
public GameObject cube1;
public GameObject cube2;
public GameObject cube3;
public GameObject cube4;
void Start()
{
Screen.orientation = ScreenOrientation.LandscapeLeft;
}
void OnGUI()
{
Vector3 V = Camera.main.WorldToScreenPoint(gameObject.transform.position);
if (GUI.Button(new Rect(V.x,Screen.height - V.y,100,30),"cube1"))
{
//do something
};
if (GUI.Button(new Rect(V.x,Screen.height - V.y,100,30),"cube2"))
{
//do something
};
if (GUI.Button(new Rect(V.x,Screen.height - V.y,100,30),"cube3"))
{
//do something
};
if (GUI.Button(new Rect(V.x,Screen.height - V.y,100,30),"cube4"))
{
//do something
};
}
Comment
The position of the buttons is relative to the gameObject with this script on it. Not relative to the cubes.
Answer by robertbu · Feb 27, 2013 at 07:56 PM
You are on the right track. You need to convert the world coordinates for each cube to screen coordinates. Try this:
void OnGUI()
{
Vector3 V = Camera.main.WorldToScreenPoint(cube1.transform.position);
if (GUI.Button(new Rect(V.x,Screen.height - V.y,100,30),"cube1"))
{
//do something
}
V = Camera.main.WorldToScreenPoint(cube2.transform.position);
if (GUI.Button(new Rect(V.x,Screen.height - V.y,100,30),"cube2"))
{
//do something
}
V = Camera.main.WorldToScreenPoint(cube3.transform.position);
if (GUI.Button(new Rect(V.x,Screen.height - V.y,100,30),"cube3"))
{
//do something
}
V = Camera.main.WorldToScreenPoint(cube4.transform.position);
if (GUI.Button(new Rect(V.x,Screen.height - V.y,100,30),"cube4"))
{
//do something
}
}
Note, your code will anchor the upper left corner of the GUI.Button to the center point of the object. To anchor them on centers, you will need to offset V by 1/2 of the button width and height before making the GUI.Button() call.