- Home /
health bar script please help
hello im having trouble making the player die when his health reaches 0 this is my script just need help with the die part here is my script:
var currentHealth = 100;
var maxHealth = 100;
var minHealth = 1;
if(currentHealth <= minHealth);
currentHealth = 0;
if(currentHealth >= maxHealth);
currentHealth = 100;
Answer by Montraydavis · Oct 29, 2012 at 12:41 AM
//Code detect death
var health : float = 100 ;
function Update ( )
{
if ( Mathf.Ceil ( health ) == 0 )
{
PlayerIsDead . . . .
}else{
health -= 1 * Time.deltaTime ;
}
}
Um what? So you'll die in 100s no matter what?
Also -- don't use update events if you can help it. Used FixedUpdate -- less overhead. For something like this you could even thread (coroutine) the code and only wake up every 0.1s or so and have even less overhead.
I understand. This was somewhat a starting point, or example more than a solution . Thanks for the suggestion as well. I will keep that in $$anonymous$$d.
You are welcome! If you do not $$anonymous$$d, mark the answer as answered, and a thumbs up ;) . Thanks for supporting Unity.
Answer by podperson · Oct 29, 2012 at 12:53 AM
Simple solution:
function FixedUpdate(){
if( currentHealth <= minHealth ){
// player is dead -- careful this doesn't get called over and over!
}
}
Here's a coroutine solution. You call CheckIfDead() once and it sits in the background and checks every so often.
function Start(){
...
CheckIfDead();
}
function CheckIfDead(){
while( currentHealth > minHealth ){
yield WaitForSeconds(0.1); // check to see if player has died ever 0.1s
}
// this code executes when the character is dead
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How to make a player die after health reaches 0 3 Answers
Add spawn to script [Multiplayer] 0 Answers
Life Player loads another level 1 Answer