[Solved] Trouble Increasing Lives in Real Time

Hello fellow screen-starers,

I am working on a basic live system to increase lives every X minutes, even when the game is closed. I have looked on YouTube, Reddit, Google, forums, etc. but cannot seem to get my script correct or find one that isnt outdated.

My issue: The lives will go up, but insanely fast. I am going to cap it with a maxLives int at like 30 but regardless it would hit that in less than a second instead of the time i want it to (many minutes). If i raise the minutesBetweenFills variable to a certain point it just stops at some number (in the thousands). In my code you will see that the lives get increased by amount which is calculated as such:

int amount = timeSinceEnergyFill.Minutes / minutesBetweenFills;

Below is the whole script i basically (entirely) copied from a reddit page since I haven’t worked with this ever before and have been testing various code.

public class Test_IncreaseLivesOverTime : MonoBehaviour {

    [SerializeField]
    private int lives = 0;
    [SerializeField]
    private int minutesBetweenFills = 3;
    private DateTime lastLifeFill;


    public TextMeshPro largeText;

    private void Start()
    {
        lastLifeFill = DateTime.Parse(PlayerPrefs.GetString("lastLifeFill", DateTime.Now.ToString()));
    }

    private void Update()
    {
      
        TimeSpan timeSinceLifeFill = (DateTime.Now - lastLifeFill);
        if(timeSinceLifeFill > TimeSpan.FromMinutes(minutesBetweenFills))
        {
            int amount = timeSinceLifeFill.Minutes / minutesBetweenFills;
            lives += amount;
            lastLifeFill -= TimeSpan.FromMinutes(minutesBetweenFills * amount);
            PlayerPrefs.SetString("lastLifeFill", lastLifeFill.ToString());
        }

        largeText.text = lives.ToString();

    }

}

Any help pointing me in the right direction shall be rewarded with praise and compliments.

Thanks

Try something like this (pseudocode):

while( now > lastFillTime + fillTimeSpan ) {
  lives += 1;
  lastFillTime += fillTimeSpan;
}

Or if you don’t want a loop:

if( now > lastFillTime + fillTimeSpan ) {
  lives += Mathf.Floor( ( now - lastFillTime ) / fillTimeSpan );
  lastFillTime = now; // or lastFillTime += fillTimeSpan * Mathf.Floor( ( now - lastFillTime ) / fillTimeSpan )
}

I wasnt able to implement your code as i was having trouble with variable types. But i found a very low watch count video on YouTube that was very good and helped me a ton. I highly recommend it if someone is looking for a solution to this.