Search Unity

Making the script do something when health reaches 0

Discussion in 'Scripting' started by DanProd, Feb 16, 2019.

  1. DanProd

    DanProd

    Joined:
    Dec 23, 2017
    Posts:
    6
    I dont exactly know where to put an if statement on the script and how to, i just want it to do something like this:
    -When player health reaches 0, it would delete player (script is attached to it) and summon/spawn a new prefab

    Here is the script:
     
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class PlayerHealth : MonoBehaviour
    {

    public int maxHealth;
    public int currentHealth;

    void Start()
    {

    currentHealth = maxHealth;

    }

    void Update()
    {
    //My suspicions that the if statement would be here right?
    }

    public void DamagePlayer(int Hurt, Vector3 direction)
    {
    currentHealth -= Hurt;

    }
    public void HealPlayer(int Aid, Vector3 direction)
    {
    currentHealth += Aid;

    }

    }
     
  2. DanProd

    DanProd

    Joined:
    Dec 23, 2017
    Posts:
    6
    Im super new in this, so forgive me for my silly questions
     
  3. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    Well, you could put it in Update() if you want to check constantly. That might be useful if there are a lot of different things in the game could could modify the health in unpredictable ways.

    But if the only time the player is supposed to get hurt is when the DamagePlayer() function is called, then it might be better to put the check there. That way you don't need to check as often.

    Also, remember that something like "if (currentHealth <= 0)" will tell you when health is zero or less, but not when health becomes zero or less. If you want to know whether the health just changed from being positive to being non-positive, you also need to check the previous value. (That would be easier to do in the DamagePlayer() function; to do it in Update(), you'd need an extra variable that keeps track of what health was last time you checked.)