- Home /
How to render subtexture on GUI
I want to have a health bar on screen. It's texture is a transition from red to green (left to right). And when the player's health is full, the entire texture is rendered to the bar on screen; and when the player lose health, only the left region of the texture will be used, thus player can see the bar become shortened and don't have the green part any more.
Usually it should be implemented as rendering a sub-texture, by dynamically changing the UV of each vertices on the bar. I checked the GUI classes (GUITexture, GUI.DrawTexture, Texture2D, etc.) but could not found where I might setup the UV, or set the rect of texture region that use for GUI rendering.
What's the best way to achieve that?
Thank you very much :)
Answer by Statement · Dec 15, 2010 at 02:14 AM
Simplest solution I come to think of doesn't require texture handling at all.
Just draw the health bar twice. One time for the "red color" and one time for the "green color", where the green color is drawn on top of the red. (I am thinking classical health bars that have a green/red portion of it.
Simply do this by calling GUI.Label and supply width as maxWidth * healthPercentage for the second (green) overlay. You can set a texture on the label.
The end result should be a very simple health bar with a red and a green part.
If you want to have "rounded edges" you can do the same procedure but instead of setting the second labels width, you can place the second label in a gui area (that clips the second label). This is probably what you want to do.
What I wanted is a smooth transition from red to green. However, since I don't have to make the invisible part of health bar transparent, similar method could be used by drawing the full health bar then over-drawing the invisible part with a background color.
Answer by doomprodigy · Dec 15, 2010 at 04:51 AM
If you want it to transition from green to red in a blocky format (not smoothly) you could do a script which renders a different texture when the health is at a certain amount. it wouldn't be smooth such as Statements. Just depends on what you want.
I can provide a script example of this if need be.