While the first prototype of a user interface often simply displays game parameters as strings, engaging interfaces usually require customized graphical representations. A straightforward technique is to display an icon for each value of an integer, for example, a stickman, a heart, or ship for each life left, a bullet or magazine for ammo, and so on.
To display images instead of integer numbers, please follow these steps:
// file: PlayerGUI.cs using UnityEngine; using System.Collections; public class PlayerGUI : MonoBehaviour { public Texture heartImage; private int livesLeft = 5; private void OnGUI() { Rect r = new Rect(0,0,Screen.width, Screen.height); GUILayout.BeginArea(r); GUILayout.BeginHorizontal(); ImagesForInteger(livesLeft, heartImage); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.EndArea(); } private void ImagesForInteger(int total, Texture icon) { for(int i=0; i < total; i++) { GUILayout.Label(icon); } } }
A public Texture
variable will store a heart image. A private livesLeft
integer variable stores the game parameter to be graphically represented.
The OnGUI()
method sets up a basic GUILayout
area that will display contents horizontally, and left aligned (via an Area
, Begin-End Horizontal
, and a FlexibleSpace
after the contents are displayed). A call is made to the ImagesForInteger()
method, passing in the livesLeft
integer and the heart Texture
.
The ImagesForInteger()
method is a straightforward for
loop, which repeatedly displays the provided image argument via GUILayout.Label()
. The image is displayed as many times as defined by the integer argument total.
Here are some details you don't want to miss:
3.142.156.235