Arthur Belkin
Arthur Belkin

Reputation: 135

Deplete set value every X second in Update method

I'd like to deplete value of health from set value every 1 second in Update method. I wrote the code, but it seems like it depletes faster than 1 second.

In an Update method, I call:

if (Hunger <= 0.0f)
{
    userHealth -= HealthDepletionValue * Time.deltaTime;
}

Which should deplete set value of HealthDepletionValue every second Time.deltaTime.

When I run the game, it depletes HealthDepletionValue every 0.1 second or something along those lines. But surely not every 1 second, like I want to.

Did I miss something?

Upvotes: 0

Views: 439

Answers (3)

CaTs
CaTs

Reputation: 1323

Alternatively you could use a Coroutine and the WaitForSeconds class.

public void Start () {
    StartCoroutine(DepleteHealth(TimeSpan.FromSeconds(1), 5));
}

public IEnumerator DepleteHealth (TimeSpan frequency, int loss) {
   var wait = new WaitForSeconds((float)frequency.TotalSeconds());
   while(true) {
        userHealth -= loss;
        yield return wait;
   }
}

This can be stopped and started pretty easily.

Upvotes: 1

devNull
devNull

Reputation: 4219

As stated in this post, Update() runs once per frame. So if you're game is running 30 frames/second, then Update() will execute 30 times/second.

To specify a function to be executed every x seconds, you can use InvokeRepeating. To do this, put the logic you want executed every second into it's own method:

void DepleteHealth()
{
    if (Hunger <= 0.0f)
    {
        userHealth -= HealthDepletionValue * Time.deltaTime;
    }
}

And then in the Start() method, call InvokeRepeating, passing in your method name and the number of seconds between execution of said method:

void Start()
{
    InvokeRepeating("DepleteHealth", 1.0f, 1.0f);
}

The post above also shows alternative ways to handle this. Including tracking a second counter within the Update() method, to ensure that you're logic is only executed if the counter has passed a full second.

Upvotes: 5

ryeMoss
ryeMoss

Reputation: 4343

Another option to InvokeRepeating would be to create your own timer.

float timer = 0;

Update()
{
  if (Hunger <= 0.0f)
  {
    timer += time.deltaTime;
    if (timer > 1f){
        userHealth -= HealthDepletionValue;
        timer = 0; //reset timer
    }
  }
}

Upvotes: 2

Related Questions