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 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 () {
}
}
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;”
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.
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.
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;
}
}
}