hey guys was just wondering how do i make my player die and respawn after the healthbar reaches 0
This is the code:
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;
public float healthBarLengh;
// Use this for initialization
void Start () {
healthBarLengh = Screen.width / 2;
}
// update is called once per frame
void update () {
AddjustCurrentHealth(0);
}
void OnGUI() {
GUI.Box(new Rect(10, 40, healthBarLengh, 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;
healthBarLengh = (Screen.width / 2) * (curHealth / (float)maxHealth);
}
}
save
2
You already have the (curHealth < 0) statement, call for a function inside that.
if(curHealth < 0) {
curHealth = 0;
KillPlayer();
}
public void KillPlayer() {
// Play death animation etc.
// Restart level or change position of player
}
Here is the fixed script.
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;
public float healthBarLengh;
// Use this for initialization
void Start () {
healthBarLengh = Screen.width / 2;
}
// update is called once per frame
private void update () {
AddjustCurrentHealth(0);
}
private void OnGUI() {
GUI.Box(new Rect(10, 40, healthBarLengh, 20), curHealth + "/" + maxHealth);
}
public void AddjustCurrentHealth(int adj) {
curHealth += adj;
if(curHealth < 0) {
KillPlayer();
}
if(curHealth > maxHealth)
curHealth = maxHealth;
if(maxHealth < 1)
maxHealth = 1;
healthBarLengh = (Screen.width / 2) * (curHealth / (float)maxHealth);
}
public void KillPlayer() {
// Play death animation etc.
// Restart level or change position of player
}
}