- Home /
Opening a level when dead
i have got a script which is a gui health bar but when it gets to 0 i want to be able to load the end game sequense hear is the script:
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);
} if(curHealth < 0)
Application.LoadLevel("game over");
}
What happens when you try to use this code? Do you get a compile-time error, or does it fail somehow while it is running.
Answer by Silverfell 1 · Feb 18, 2011 at 12:58 PM
As well as the Bampf's suggestion, I think you might have a logic problem as well.
if(curHealth < 0)
curHealth = 0;
resets curHealth to 0. Therefore, your Application.LoadLevel will never be triggered. try instead:
public void AddjustCurrentHealth(int adj) { curHealth += adj;
if(curHealth <= 0) { curHealth = 0; Application.LoadLevel("game over");}
if(curHealth > maxHealth) curHealth = maxHealth;
if(maxHealth < 1) maxHealth = 1;
healthBarLength = (Screen.width / 2) * (curHealth / (float)maxHealth);
}
Answer by Bampf · Feb 18, 2011 at 11:48 AM
Looks like the check at the for curHealth < 0 isn't inside any of the procedures. In C# you can't do that. (You can do it in Unity Javascript, but it's the same as putting those lines inside of Awake() - they will run first, which is not when you want to do the health check.)
Try moving it up a line, into the AdjustCurrentHealth method:
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);
if(curHealth < 0)
Application.LoadLevel("game over");
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Follow-up from previous question: "Load levels randomly" 0 Answers
Need Help Ending A Game - Alphabet Game 1 Answer
Weird LoadLevel Error 1 Answer