- Home /
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 () {
AddjustCurrentHealth(0);
}
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);
}
}
texture.Apply();
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.
Answer by captaincrunch80 · Apr 12, 2012 at 12:26 AM
Hi there!
Check out the gui tutorial: http://unity3d.com/support/documentation/Components/gui-Layout.html
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.BeginHorizontal();
GUILayout.FlexibleSpace ();
GUILayout.Label("my centered text");
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal();
GUILayout.EndArea();
}
Another way would be to calculate the text size and center it manually with a Rect. (see GUIStyle.CalcSize for that)
Ohhh thanks for this answer. This Help so much to undestand a center text in a box, thanks
@Helienio - If this answered your question, click on the checkmark to the left of the question to accept it.
Your answer
Follow this Question
Related Questions
How to make a texture cover an entire GUI box 0 Answers
Create GUI Texture using GUI Layout 2 Answers
I need help with the player's health points 1 Answer
How do I make a custom health bar? 0 Answers