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");
}
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);
}
Bampf
February 18, 2011, 11:48am
2
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");
}
}