- Home /
How do i make my player die?
Okay so i have hunger and thirst that deplete my health when they reach 0 but my player doesn't die when his health reaches 0, how do i do this? my health script is in C#(i think i made it look like code):
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour { public float maxHealth = 100f; public float curHealth = 100f;
public float healthBarLength; private Thirst thirst; private Hunger hunger;
// Use this for initialization void Start () { healthBarLength = Screen.width / 2; thirst = GetComponent(typeof(Thirst)) as Thirst; hunger = GetComponent(typeof(Hunger)) as Hunger; } // Update is called once per frame void Update () { AddjustCurrentHealth(0); if (thirst.thirstLevel <= 0 || hunger.hungerLevel <= 0) { //variable declaring delay of however many seconds //int delay = 10; //delay-= 1; //if (delay == 0){ //if(delay = 0) execute following line curHealth -= 0.01f; //}
} }
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); } }
Answer by fafase · Jul 04, 2012 at 08:06 AM
Personal opinion, I would not destroy the main character, just a point of view, I would rather respawn it. Main characters generally have a lot of information and many things happens in the Start(), particularly expensive Find() functions. Destroying and instantiating a new character might cause some lagging. If you simply reposition him somewhere with reinitialization of the variables, it won't show. On top of that, other scripts like enemies are probably using the character for target or other purpose, you could get a Null reference if you destroy the object.
function Update(){
if(health<=0)
Die();
}
function Die(){
transform.position = Vector3(x,y,z);
health = 100;
// other codes
}
$$anonymous$$y health script is in c# so when I try to call my health variable it throws a fit. Would it be the same thing in c# as it is in javascript? I'm not the best at translating code between languages.
Answer by BeHappy · Jul 04, 2012 at 07:42 AM
Have a check for,
if(health == 0)
{
Destroy(gameobject);
}
That will destroy the player.
as health is a float, I would use <= 0 e.g.
if(health <= 0)
{
Destroy(gameobject);
}