- Home /
How to add texture in onGUI()
I have made a working health bar that takes damage and regenerates over time, using two GUI rectangles. However, since the colors are only green when health is > 50% and red when health is <50%.I'm confused on how I would add texture to the health bars? How would I make the texture and implement it and make sure it works?
Here's the code
// draw the health bar
//draw the background:
if(gameObject.GetComponent<Status> ().health > 50.0f) {
InitStyles (Color.green);
} else {
InitStyles(Color.red);
}
GUI.BeginGroup(new Rect(pos.x, pos.y, size.x, size.y));
GUI.Box(new Rect(0,0, size.x, size.y), emptyTex);
//draw the filled-in part:
GUI.BeginGroup(new Rect(0,0, gameObject.GetComponent<Status> ().health, size.y));//gameObject.GetComponent<Status> ().health?
GUI.Box(new Rect(0,0, size.x, size.y), fullTex, currentStyle);
GUI.EndGroup();
GUI.EndGroup();
// draw the mana bar
//draw the background:
InitStyles (Color.blue);
GUI.BeginGroup(new Rect(pos.x, pos.y + size.y, size.x, size.y));
GUI.Box(new Rect(0,0, size.x, size.y), emptyTex);
//draw the filled-in part:
GUI.BeginGroup(new Rect(0,0, gameObject.GetComponent<Status> ().mana, size.y));//gameObject.GetComponent<Status> ().health?
GUI.Box(new Rect(0,0, size.x, size.y), fullTex, currentStyle);
GUI.EndGroup();
GUI.EndGroup();
// draw the stamina (rage) bar
//draw the background:
InitStyles (Color.magenta);
GUI.BeginGroup(new Rect(pos.x, pos.y + 2 * size.y, size.x, size.y));
GUI.Box(new Rect(0,0, size.x, size.y), emptyTex);
//draw the filled-in part:
GUI.BeginGroup(new Rect(0,0, gameObject.GetComponent<Status> ().rage, size.y));//gameObject.GetComponent<Status> ().health?
GUI.Box(new Rect(0,0, size.x, size.y), fullTex, currentStyle);
GUI.EndGroup();
GUI.EndGroup();
private void InitStyles(Color c)
{
//if (currentStyle == null) {
currentStyle = new GUIStyle (GUI.skin.box);
currentStyle.normal.background = MakeTex (2, 2, c);
//}
}
private Texture2D MakeTex( int width, int height, Color col )
{
Color[] pix = new Color[width * height];
for( int i = 0; i < pix.Length; ++i )
{
pix[ i ] = col;
}
Texture2D result = new Texture2D( width, height );
result.SetPixels( pix );
result.Apply();
return result;
}
Comment