1
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ What about adding an image over top of it (that appears the same as the background)? \$\endgroup\$ – ChargingPun May 6 '14 at 14:38
2
\$\begingroup\$

You can do this via script, using GUI.DrawTextureWithTexCoords

This lets you clip-out a rectangle of the texture you want to draw onto the screen.

For instance (within an OnGUI() method)....

float healthFraction = ((float)hitPoints)/maxHitPoints;

Rect screenRect = new Rect(xPosition, yPosition, healthFraction * width, height);
Rect textureRect = new Rect(0, 0, healthFraction, 1);

GUI.DrawTextureWithTexCoords(screenRect, texture, textureRect);
|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

Or if you're using NGUI, you can use UISlider for this. It'll automatically handle vertical, horizontal and radial progression using part of the image.

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.