- Home /
How to prevent losing multiple lives at zero health?
Hi all, I am having the problem that between the time my player's health reaches zero and the death animation finishes, if the player collides with another enemy, the player will continue to lose lives. Here is my code if anyone has any suggestions. I tried a coroutine with yield WaitForSeconds in the HealthScript, but that didn't seem to help:
HealthScript:
public void Damage(int damageCount)//Inflicts damage
{
hp -= damageCount;
if (hp <= 0 && this.gameObject.tag == "Player") {
MainScript playerLives = this.GetComponent<MainScript> ();
playerLives.UpdateLives (1); //player lives minus one
}
}
MainScript:
public void UpdateLives(int livesLost){
playerLives -= livesLost;
HealthScript playerHealth = this.GetComponent<HealthScript> (); //get player health script
if (playerLives > 0){
StartCoroutine ("DieAnim");
}
private IEnumerator DieAnim ()
{
animator.SetInteger ("AnimState", 1);
yield return new WaitForSeconds(1);//death animation plays
Application.LoadLevel (Application.loadedLevel);//reload the current level
}
Answer by hav_ngs_ru · Dec 13, 2014 at 08:48 AM
fire some flag in your Coroutine, and dont decrement lives in UpdateLives if this flag is fired
UpdateLives() {
if(!iAmDying) {
...
}
}
DieAnim() {
iAmDying = true;
...
}
Answer by f4bo · Dec 13, 2014 at 09:31 AM
you just need to move the check
if (playerLives > 0)
in the Damage script like this:
public void Damage (int damageCount)//Inflicts damage
{
// insert check here
if (playerLives > 0) {
hp -= damageCount;
if (hp <= 0 && this.gameObject.tag == "Player") {
MainScript playerLives = this.GetComponent<MainScript> ();
playerLives.UpdateLives (1); //player lives minus one
}
}
}
Thanks f4bo. I tried what you suggested and got this error message:
Assets/Sample Assets/2D/Scripts/HealthScript.cs(42,37): error CS0019: Operator >' cannot be applied to operands of type
$$anonymous$$ainScript' and `int'"
I tried storing 0 as a variable named $$anonymous$$Lives in the $$anonymous$$ainscript, which seemed to give the same result. I'm sure there's a way to tweak it and make it work, but I have hav_ngs_ru's method working :)
looking your script above I thought playerLives was an integer storing the number of lives - anyhow I see you've solved the issue so never $$anonymous$$d.
Your answer
Follow this Question
Related Questions
Help with player death on collision! 2 Answers
Cant Find Destruction Code? 1 Answer
OnCollisionEnter issues 3 Answers