Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Problems with decreasing health.

Discussion in 'Scripting' started by RiseBestgirl, Dec 17, 2014.

  1. RiseBestgirl

    RiseBestgirl

    Joined:
    Dec 17, 2014
    Posts:
    10
    I am making a small horror game to practice in unity. I'm trying to have health decrease if you have your flashlight. If the flashlight is off the player is supposed to have their health slowly decrease until they can turn the light back on or get into a well let area.

    The problem is I can't get the health to decrease slowly over time with the Time.Deltatime code to work.

    Here's the code \

    if (light.enabled == false)

    {

    GameObject player = GameObject.Find ("First Person Controller");
    PlayerHealth playerhealth = player.GetComponent<PlayerHealth> ();
    playerhealth.curHealth -= Time.deltaTime/10;

    }
     
  2. Sbizz

    Sbizz

    Joined:
    Oct 2, 2014
    Posts:
    250
    Hmm.

    What kind of variable is "curHealth" ; int or float ? Also, Time.deltaTime/10 is a very small number (0.01, even less).
     
  3. RiseBestgirl

    RiseBestgirl

    Joined:
    Dec 17, 2014
    Posts:
    10
    curHealth is a int, as for the deltatime/10, that was because I was messing around and trying to get it to work.


    Here's the health 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 /1;

    }

    // Update is called once per frame
    void Update () {

    AddjustCurrentHealth(0);
    }

    void OnGUI()
    {

    GUI.Box (new Rect(10,0, 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);

    }
    }
     
    Last edited: Dec 18, 2014
  4. Sbizz

    Sbizz

    Joined:
    Oct 2, 2014
    Posts:
    250
    Please, use the tags [*code=CSharp][/code].

    The thing is you're attempting to convert a float to an int. When you do "Time.deltaTime / 10", the result should be > 0 and < 1 (0.01 like I said). But "curHealth" is an int so the value will be cast and you'll get .. 0 ! You're trying to remove 0 from curHealth (basically, you're removing nothing).

    Either you change your curHealth to float or you set a minimum value when decreasing player's health (like 1).