OnGUI - Generating a health bar?

I have a piece of code that I am trying to use to display a number of hearts on the player’s screen as a health “bar”, the number of which being able to be changed (think Legend of Zelda).

I’ve written this code, which accepts my two textures (healthFull being the inside of the individual heart and healthEmpty being the frame in which it is inset). When the player loses health (say, from 10 health to 9), the tenth heart would just be the frame while the other 9 would be filled - See “LIFE”. The two textures are each 9 pixels by 8 pixels. I have attempted to place 3 pixels padding between each heart. My code(C#):

using UnityEngine;
using System.Collections;

public class PlayerHealthLF : MonoBehaviour {

	public int maxHealth;
	public int health;

	public Texture2D healthFull;
	public Texture2D healthEmpty;

	// Use this for initialization
	void Start () {
		health = maxHealth;
	}

	// Update is called once per frame
	void Update () {
		TakeDamage(0);
	}
	
	// Initialize GUI
	void OnGUI () {
		for(int e = 0; e > maxHealth; e++){
			GUI.DrawTexture(new Rect((9 * e) + 3, Screen.height - 11, 9, 8), healthEmpty);
		}
		for(int f = 0; f > health; f++){
			GUI.DrawTexture(new Rect((9 * f) + 3, Screen.height - 11, 9, 8), healthFull);
		}
	}

	// Use this to take damage
	public void TakeDamage(int damage){
		health -= damage;
	}
}

…And nothing is displayed. Perhaps a more trained eye can reveal to me why exactly this isn’t working - a thousand thanks!

Your problem is in your ‘for’ loops. You have the condition backwards. The ‘>’ should be ‘<’. So line 24 should be:

  for (int e = 0; e < maxHealth; e++) {

and line 27 should be:

  for (int f = 0; f < health; f++) {

If you fix that and have maxHealth and health initialized, you code will work.

Note this is not the typical way to use GUI to display things like this. Typically you would create two textures. One would be strip of all empty blocks. The second would be a strip of hearts. Then you would use GUI.DrawTextureWithTexCoords() to draw however much of each texture you needed. While your solution works, you generate a draw call for every GUI.Texture call. While the other solution uses a max of two draw calls. Many draw calls can have a significant impact on a mobile game.