Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Issue with time not being consistent when regenerating Stamina

Discussion in 'Scripting' started by mayu_polo, Apr 16, 2021.

  1. mayu_polo

    mayu_polo

    Joined:
    Feb 21, 2014
    Posts:
    3
    Hi all, Im teaching myself Unity and C# by creating an idle game. I have an issue related to Time.deltaTime. The player has an amount of Stamina (or energy) to do actions. When the stamina is not at max, I want it to regenerate over time based on a staminaRegenRate variable. I got it kind of working, however, for some reason, the rate at which the stamina regenerates increases as I consume more stamina. So when I consume 1 Stamina, the regeneration rate seems correct, but if I keep consuming Stamina, the speed at which it regenerates increases. I did a debug.log for the delta time and noticed that it fluctuated between 0.027 up to 0.068 at times. Would appreciate some help trying to debug this. Here are the two relevant scripts: https://controlc.com/278ff339 and https://controlc.com/6d23f25d Thanks!
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    You're starting a new instance of the RegenStamina coroutine every time TakeStamina is called. I believe this means that you are ending up with multiple instances of the coroutine all adding stamina each frame, when what you want is just 1 instance of the coroutine. This kind of bug is actually the reason why I personally favor using Update for this kind of thing, but you could fix this pretty easy here. Just at the start of RefenStamina, set some bool value to true to indicate that the coroutine is already running. Don't launch another instance of the coroutine if that bool is already true. At the end of the coroutine, set the bool to false.

    On Time.deltaTime, it is supposed to fluctuate when FPS fluctuates. A 0.068 deltaTime value means your game has dropped to about 14 FPS. When FPS is low, you will see the stamina regenerate more per frame because more time is passing for each individual frame than when FPS is higher (this is ignoring the likely multiple coroutine issue above). So for each second of time, you should see approximately the same amount of stamina regen.
     
    mayu_polo likes this.
  3. mayu_polo

    mayu_polo

    Joined:
    Feb 21, 2014
    Posts:
    3
    Thank you so much that worked like a charm!
     
    Joe-Censored likes this.