0

I have a Health Bar in my Unity game and it's implemented as a GUITexture with gradient image from red to green.

enter image description here

Now I can reduce it's width from max width to 0, but is still scaled gradient.

public void UpdateHealthBar(int hitPoints) {
    healthBar.pixelInset = new Rect(
        healthBar.pixelInset.x, healthBar.pixelInset.y,
        3* hitPoints, healthBar.pixelInset.height);
}

enter image description here

But I want to hide (make transparent) the right part of this health bar in game progress.

enter image description here

How can I do this? Thanks!

Steven
  • 166,672
  • 24
  • 332
  • 435
Dmytro Zarezenko
  • 10,526
  • 11
  • 62
  • 104
  • Have a look at embedding your drawtexture call into a GUI.BeginGroup. If I have some time I might code something up later on, but it will be good to see what you're currently doing. – Bart May 06 '14 at 13:58
  • I have added all details into my question. – Dmytro Zarezenko May 06 '14 at 14:10

2 Answers2

1

Or you can use GUI.DrawTextureWithTexCoords()

public Texture2D texture;
public float hp = 100f;
public const float hpMax = 100f;

void OnGUI()
{
    GUI.DrawTextureWithTexCoords (new Rect (0, 0, hp, 20), texture, new Rect (0f, 0f, hp/hpMax, 1f));
}
Verv
  • 763
  • 6
  • 9
0

As Bart suggested, you can use GUI.BeginGroup

Here is an example

public Texture2D texture;
public Rect textureCrop = new Rect( 0.1f, 0.1f, 0.5f, 0.25f );
public Vector2 position = new Vector2( 10, 10 );

void OnGUI()
{
    GUI.BeginGroup( new Rect( position.x, position.y, texture.width * textureCrop.width, texture.height * textureCrop.height ) );
    GUI.DrawTexture( new Rect( -texture.width * textureCrop.x, -texture.height * textureCrop.y, texture.width, texture.height ), texture );
    GUI.EndGroup();
}
jparimaa
  • 1,964
  • 15
  • 19