- Home /
Question by
davidflynn2 · Aug 22, 2012 at 09:39 PM ·
c#healthbarprograming
C# Health Bar
I have set this code up so that it uses GUI.Box to make the bar for the health. I would like to change this over so that I can get a healthBarFrame and healthBarTexture to it using graphics I have made. I am a bit new to C# and Hoping for some one to lend me a hand.
Thanks David
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;
public float healthBarLength;
// Use this for initialization
void Start () {
healthBarLength = Screen.width /2;
}
// Update is called once per frame
void Update () {
AddjustCurrentHealth(0);
}
void OnGUI(){
GUI.Box (new Rect(10,10, healthBarLength, 20), curHealth + "/" + maxHealth);
}
public void AddjustCurrentHealth(int adj){
curHealth += adj;
if(curHealth <0)
curHealth = 0;
if(curHealth > maxHealth)
curHealth = maxHealth;
if(maxHealth <1)
maxHealth = 1;
healthBarLength =(Screen.width /2) * (curHealth / (float)maxHealth);
}
}
Comment
Best Answer
Answer by termway · Aug 23, 2012 at 02:11 PM
There is an example of health bar using Texture2D in this tutorial :
http://docs.unity3d.com/Documentation/Components/gui-Layout.html
With some modification :
public class PlayerHealth : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;
public Texture2D bgImage;
public Texture2D fgImage;
public float healthBarLength;
// Use this for initialization
void Start () {
healthBarLength = Screen.width /2;
}
// Update is called once per frame
void Update () {
AddjustCurrentHealth(0);
}
void OnGUI () {
// Create one Group to contain both images
// Adjust the first 2 coordinates to place it somewhere else on-screen
GUI.BeginGroup (new Rect (0,0, healthBarLength,32));
// Draw the background image
GUI.Box (new Rect (0,0, healthBarLength,32), bgImage);
// Create a second Group which will be clipped
// We want to clip the image and not scale it, which is why we need the second Group
GUI.BeginGroup (new Rect (0,0, curHealth / maxHealth * healthBarLength, 32));
// Draw the foreground image
GUI.Box (new Rect (0,0,healthBarLength,32), fgImage);
// End both Groups
GUI.EndGroup ();
GUI.EndGroup ();
}
public void AddjustCurrentHealth(int adj){
curHealth += adj;
if(curHealth <0)
curHealth = 0;
if(curHealth > maxHealth)
curHealth = maxHealth;
if(maxHealth <1)
maxHealth = 1;
healthBarLength =(Screen.width /2) * (curHealth / (float)maxHealth);
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Creating A GUI health bar 0 Answers
How to make slider function properly after an animation? 2 Answers
Health Bar doesnt fit my float var 1 Answer