- Home /
Healt Bar Logic
so i try to make a health bar, i use GUITexture to create the bar, the width is 330 (for some reason it HAS to be like that)..
now i try to achieve how the bar could decrease on every attack that it receive.. and it's done!
but the problem is i couldn't convert the 330 into 100% bar length..
my code for attack is like this..
function Attack(){
var percenthp : float;
var tekstur : GUITexture;
var enemyhpdisplay;
var hplength ;
enemy_hp -= player_atk; //player_atk is 5 and declared in other place, so as enemyhp
//print(enemy_hp);
percenthp = (enemy_hp/enemy_maxhp)*100;
tekstur= GameObject.Find("enemyHp").GetComponent(GUITexture);
tekstur.guiTexture.pixelInset.width= percenthp;
}
so we know my healthbar width is 330, but everytime i click the attack the bar just drom from 330 width, into 95 width,.. i couldn't know how to convert it, so the width will decrease by percentage of the length.. could anybody help me ?
Have you tried a search before asking ?
http://answers.unity3d.com/questions/314754/guitexture-width-change.html
@sath i've tried it, but still couldn't achieve it..
i mean, i put the calculation on function Attack()
which i call on function OnGUI()
does i need to initialize it on function Start()
?
sorry, still not too good on algorithm.. x.x
Answer by sath · Jan 05, 2014 at 11:01 AM
Is this more helpful ?
#pragma strict
// drag the GUITexture from the Hierarchy view to this field in the Inspector:
var tekstur: GUITexture;
var enemy_hp : int = 100;
private var width330: float; // the initial healthBar width
function Start () {
width330 = tekstur.pixelInset.width;
}
function Update () {
if(Input.GetMouseButtonDown(0)){//you can Attack in OnGUI if already have a button
Attack();
}
// set the health bar width:
tekstur.pixelInset.width = width330 * enemy_hp / 100;
if (enemy_hp <= 0){ // enemy has died?
Destroy(gameObject);
}
}
function Attack(){
enemy_hp -= 5;//player_atk;
}
Also there are several ways to make a health bar (like GUI.DrawTexture)
you can watch this tutorial if you want to learn more (and have patience)
wow, cool it works ! oh my why i'm so blind with this simple math problem.. thanks @sath ! Thanks for the tutorial from youtube too, i've been watching it for about 5-8 times.. i can make it decrease just couldn't change the 330 width to become 100 on real game.. :/
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
NullReferenceException: Object reference not set to an instance of an object... 0 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How Do I Make A Health Bar 6 Answers