Game Development Reference
In-Depth Information
Listing 8-6. GUILabel.cs: Class for Rendering Text on Screen Using the GUI Framework
01 using UnityEngine;
02 using System.Collections;
03 [ExecuteInEditMode]
04 public class GUILabel : MonoBehaviour
05 {
06 //Content for label
07 public GUIContent LabelData;
08
09 //Style for label
10 public GUIStyle LabelStyle;
11
12 //Rect for label
13 public Rect LabelRegion;
14
15 //Draw label
16 void OnGUI()
17 {
18 Rect FinalRect = new Rect(LabelRegion.x * Screen.width, LabelRegion.y *
Screen.height, LabelRegion.width * Screen.width, LabelRegion.height * Screen.height);
19
20 GUI.Label(FinalRect, LabelData, LabelStyle);
21 }
22 }
Lines 07, 10, and 13. The public members LabelData , LabelStyle , and
LabelRegion have been added to define the contents of a label (what it will say),
its style (how it will look), and its positional data (where it will appear on the
screen). These properties will all be accessible and customizable through the
Object Inspector when a Label component is added to an object.
Line 20. The GUI.Label function is called on the OnGUI event to render the label
text to the screen with specified content, style, and size.
Note More information on the GUI classes can be found in the online Unity documentation at
http://docs.unity3d.com/Documentation/Components/gui-Basics.html .
We'll need the label class to display the ammo count and Player health status. For this reason,
let's add two label components to the root GUI object in the scene, by dragging and dropping the
GUILabel class onto the GUI object. Once added, configure each label through its Label Data , Label
Style and Label Region values in the Object Inspector (see Figure 8-13 ). For Label Data, the text
should be set to Health for the health label and to Ammo for the ammo label. For both labels, the
text color should be White . For the Label Style object, the Font Size should be 20 . And for the Label
Region, the position of the health label is rendered at (0.01, 0.01) , and the ammo label at (0.9, 0.01) .
Notice the positions for each label are specified in screen relative coordinates .
 
 
Search WWH ::




Custom Search