Hello
I wanted to create a healthbar GUI that has an end result like this:
This is what I have done so far but I cannot seem to get it working
using UnityEngine;
using System.Collections;
public class HealthBarTest : MonoBehaviour {
public Texture2D healthBackground;
public Texture2D healthForeground;
public Texture2D healthDamage;
public float curhp = 100f;
public float maxhp = 100f;
public float healthPercent;
private float healthBarWidth;
private int healthRegen = 20;
public double healTime = 5.0;
private bool increasing = false;
void Start(){
//setting the health to be the screen width
healthBarWidth = 100f;
}
void Update(){
adjustCurrentHealth(0);
// calculating the health as a percentage integer
healthPercent = (curhp / maxhp); // this will = 1
}
void OnGUI(){
// calculating the health and its width deduction and regeneration
int adjust = (int)curhp * (int)healthBarWidth / 100;
// displaying GUI textures
GUI.DrawTexture(new Rect(60, Screen.height - 65, healthBarWidth, 15), healthBackground); //health lost
GUI.BeginGroup(new Rect(60, Screen.height - 65, adjust, 15));//adjusting value for health
GUI.DrawTexture(new Rect(0, 0, healthBarWidth, 15), healthForeground); // current health shown
GUI.DrawTexture(new Rect(60, Screen.height - 65, healthBarWidth / (maxhp - curhp), 15), healthDamage); //health lost
//GUI.BeginGroup(new Rect(60, Screen.height - 65, adjust, 15));//adjusting value for health
//GUI.DrawTexture(new Rect(0, 0, 300, 15), healthForeground); // current health shown
GUI.EndGroup();
}
public void adjustCurrentHealth(int adj){
curhp += adj;
// deduct health for each space bar hit
if(Input.GetKeyUp("space")){
curhp-= 10f;
}
// increasing is set to true if current hp is less than the max hp
if(curhp < maxhp){
//increasing = true;
} else {
increasing = false; // if current and max are equal
}
// set to equal if current is greater than max
if(curhp > maxhp){
curhp = maxhp;
}
// initialise a countdown for healTime if condition is true
if(increasing){
healTime -= Time.deltaTime;
// reset healTime and restore current hp
if (healTime <= 0){
healTime = 5;
curhp += healthRegen;
}
}
// dead!!!
if(curhp <= 0)
curhp = 0;
increasing = false;
}
}
Thanks for any help provided.