Wednesday, June 26, 2013

Unity: Creating GUI Labels Over 3D Objects

The GUI commands built in to Unity are a fast, convenient way to present information on screen. One way to take full advantage of this is creating GUI elements that line up over 3D objects. In a standard FPS action game, for example, it could show you a monster's health and any effects that are currently active. Add a simple toggle (I prefer the question mark), and you have an easy way to turn on debug information in-game.

Here's a screenshot from Chess Heroes that shows it in action. What's shown is the type of piece and the ID of the player that owns it.


Here's the code:
bool showDebugInfoGUI;
float boxW = 150f;
float boxH = 20f;

void OnGUI ()
{
 if (showDebugInfoGUI)
 {
  // As an example, this will show the name of each untagged gameobject over itself
  // But in general, this is not a good idea!
  foreach (GameObject targetObject in GameObject.FindGameObjectsWithTag("Untagged"))
  {
   ShowObjectNameInGUIForObject (targetObject);
  }
 }
}

void ShowObjectNameInGUIForObject (GameObject targetObject)
{
 // Find the 2D position of the object using the main camera
 Vector2 boxPosition = Camera.main.WorldToScreenPoint(targetObject.transform.position);

 // "Flip" it into screen coordinates
 boxPosition.y = Screen.height - boxPosition.y;

 // Center the label over the coordinates
 boxPosition.x -= boxW * 0.5f;
 boxPosition.y -= boxH * 0.5f;

 // Draw the box label
 GUI.Box(new Rect(boxPosition.x, boxPosition.y, boxW, boxH), targetObject.name);
}

void Update ()
{
 // Toggle the labels using the forward slash key (the one with the question mark)
 // Note that this can't be put in OnGUI, as OnGUI runs twice each frame
 if (Input.GetKeyDown(KeyCode.Slash)) showDebugInfoGUI = !showDebugInfoGUI;
}

Updated September 10, 2013

3 comments:

  1. Hey Ted, I'm fairly new to unity and was attempting to use this script. but I get errors on the "bool" word. Are you using js or C#?

    Thanks

    Rick

    ReplyDelete
    Replies
    1. Sorry for the late reply, Rick! All of my examples are in C#.

      Delete
  2. Thank you very much, this helped alot!

    ReplyDelete