Center GUIContent and texture for a GUI.Box

I have this code for a health bar:

using UnityEngine;
using System.Collections;

public class PlayerHealth : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;

public float healthBarLength;

// Use this for initialization
void Start () {
	healthBarLength = Screen.width / 2;

// Update is called once per frame
void Update () {

public void OnGUI() {
	GUIStyle style = new GUIStyle();
	Texture2D texture = new Texture2D(128, 128);
	  for (int y = 0; y < texture.height; ++y)
        for (int x = 0; x < texture.width; ++x)
            float r = Random.value;
            Color color = new Color(1, 0, 0);
            texture.SetPixel(x, y, color);

    style.normal.background = texture;
	GUI.Box(new Rect(10, 10, healthBarLength, 20), new GUIContent(curHealth + "/" + maxHealth), style);

public void AddjustCurrentHealth(int adj) {
	curHealth += adj;
	if(curHealth < 0)
		curHealth = 0;
	if(curHealth > maxHealth)
		curHealth = maxHealth;
	if(maxHealth < 1)
		maxHealth = 1;
	healthBarLength = (Screen.width / 2) * (curHealth / (float)maxHealth);


I want to know how can I center the text that I put into the Gui.Box (curHealth + “/” + maxHealth), bacause it is at the left of the Box.

The other thing i want to know is how can I set a Texture for the Box instead of a Color, and add this texture from a file in Unity instead of adding it in the C# Script.

Hi there!

Check out the gui tutorial:

In the middle of this tutorial is exacly what you need for the health bar with textures.

If you dig a little deeper you can also handle text centering with GUILayout easily.
Here is a snippet that will help you get the right direction (if you use the same for schheme for Vertical alignement and give your health bar as Rect for the area, it will be in the perfect center):

// C#
    public void OnGUI() {
        GUILayout.BeginArea (new Rect (0,0,200,60));
               GUILayout.FlexibleSpace ();
               GUILayout.Label("my centered text");
               GUILayout.FlexibleSpace ();

Another way would be to calculate the text size and center it manually with a Rect. (see GUIStyle.CalcSize for that)