How to make a player die after health reaches 0

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);
}

}

Post your full script as it is now.

2 Answers

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
}

To respawn you could just create a prefab of you player and Instantiate a new GameObject at some waypoint. http://docs.unity3d.com/Documentation/ScriptReference/Object.Instantiate.html

Keep getting a 'Unexpected Symbol 'public' nothing seems to fix it

that could mean a missing bracket

public class PlayerHealth : MonoBehaviour { public int maxHealth = 100; public int curHealth = 100; public float healthBarLengh; //} you need a bracket right here // Use this for initialization void Start () { healthBarLengh = Screen.width / 2; }

@joeyaaaaa How would that fix it?

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
	}
}

Sorry just edited, realized you completely screwed it up :D

Thanks so much! Working fine! can probably tell im not the programmer in the project, one last question! how would i go about getting the player to respawn?