Advertisement
NPSF3000

Stupidly Simple Unity Healthbar

Jul 10th, 2011
5,415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.31 KB | None | 0 0
  1. //  Created By NPSF3000 (NPSF3001 randomgarbage gmail.com)
  2. //  Free for all use, use at own risk.
  3. //  Simple experiment, not much testing or research hs gone into this.
  4. //  Attribution preferred.
  5.  
  6.  
  7. using UnityEngine;
  8. using System.Collections;
  9.  
  10. public class HealthBar : MonoBehaviour
  11. {
  12.  
  13.     Rect box = new Rect(10, 10, 100, 20);
  14.  
  15.     private Texture2D background;
  16.     private Texture2D foreground;
  17.  
  18.     public float health = 50;
  19.     public int maxHealth = 100;
  20.  
  21.     void Start()
  22.     {
  23.  
  24.         background = new Texture2D(1, 1, TextureFormat.RGB24, false);
  25.         foreground = new Texture2D(1, 1, TextureFormat.RGB24, false);
  26.  
  27.         background.SetPixel(0, 0, Color.red);
  28.         foreground.SetPixel(0, 0, Color.green);
  29.  
  30.         background.Apply();
  31.         foreground.Apply();
  32.     }
  33.  
  34.     void Update()
  35.     {
  36.         health += Input.GetAxisRaw("Horizontal");
  37.         if (health < 0) health = 0;
  38.         if (health > maxHealth) health = maxHealth;
  39.     }
  40.  
  41.     void OnGUI()
  42.     {
  43.         GUI.BeginGroup(box);
  44.         {
  45.             GUI.DrawTexture(new Rect(0, 0, box.width, box.height), background, ScaleMode.StretchToFill);
  46.             GUI.DrawTexture(new Rect(0, 0, box.width*health/maxHealth, box.height), foreground, ScaleMode.StretchToFill);
  47.         }
  48.         GUI.EndGroup(); ;
  49.     }
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement