Noob needs help with Time.deltaTime ))

Hi, I’m using this simple script for continuously lowering my players health. I should probably implement time.deltatime to make that fall rate constant. I looked at different examples of codes with time.deltatime but I’m still not able to put it in my code :smile: Can you please help?


using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;

public class PlayerManager : MonoBehaviour {

public static int health = 1000;
public GameObject player;
public Slider healthBar;

// Use this for initialization
void Start ()
{
InvokeRepeating("ReduceHealth",1,1);

}

void ReduceHealth()
{
health = health - 1;
healthBar.value = health;
if (health <= 0)
{
Application.Quit();
}
}

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

}
}

First, use code tags, it makes your code much easier to read.

But basically, you have a “amount per second”, and you need to convert that to “amount this frame”. Multiplying by Time.deltaTime is how you do that. So instead of your invoke, you can just call ReduceHealth from Update, and use “health = health - 1f * Time.deltaTime;”

I’m trying but I’m not even able to to that… not kidding here :smile:

two things.

  1. you are asking for help using Time.deltaTime, I can only assume that you are asking that the health lower from 1000 to 0 smoothly, however, you are using a int, and not a float. This means that using Time.deltaTime will not help you.
  2. The implementation of InvokeRepeating works perfectly for an int in this case.

and… of course, rather than be useless and say, you can’t do it that way… you actually can. :wink:

using System.Collections;

using UnityEngine;
using UnityEngine.UI;

public class PlayerManager : MonoBehaviour
{
    public static float health = 1000;
    public GameObject player;
    public Slider healthBar;

    // Use this for initialization
    void Start()
    {
        healthBar.maxValue = health;
        StartCoroutine(ReduceHealth(1));

    }

    IEnumerator ReduceHealth(float rate)
    {
        var cont = true;
        if (rate <= 0) rate = 1;

        while (cont)
        {
            health -= (1f / rate) * Time.deltaTime;
            healthBar.value = health;
            if (health <= 0)
            {
                Application.Quit();
                cont = false;
            }
            yield return 0;
        }
    }
}

Thanks! That sounds good but what do you mean by “call from update”? feeling dumb here…

Wow! Thanks I will try that now!

You are my god :smile: I dont understand half of it but it works like charm! Thanks!