Energy refill script bug fix

Hi guys. I am making an energy refill script for my game right now. What it does is it detects whenever the player’s energy is below 20 (the maximum amount) and then counts down from 30 seconds. (I’ve programmed all of the not-in-game stuff and in the real game it’s obviously going to take longer than 30 seconds to refill, I’ve made it 30 seconds for test purposes) However, I find that this doesn’t work sometimes and I think i know why. I use DateTime.Now.Second for this a lot and if I exit my game in the second half of a minute, by the time 30 seconds has passed it will already be the beginning of the next minute and the seconds will be lower and therefore will not meet my condition of if (PlayerPrefs.GetInt ("ExitTime") + 30 < System.DateTime.Now.Second) { Reference.energy += 2; }

What property should I use to get the time in seconds which doesn’t restart to 0 every minute?
Thanks!

I would not use the System.DateTime methods for those things. Unity has a good solution for time tracking, located in the Time class:

You can use Time.time for scaled time since the start of the game (it is influenced by the timeScale) or Time.unscaledTime if you want to use realtme values.

My implementation may not be the best, but it should give you a general idea. Instead of MaxValue you could introduce a bool variable that checks if a refill is pending or not. And only set the refillStartTime if no refill is already pending:

float refillStartTime = float.MaxValue;

private void refill(){
	if (refillStartTime == float.MaxValue && energy < 20){
		refillStartTime = Time.unscaledTime;
		//sets the start time to a specific value below the max float value, but only if the start time has not been set before. 
	}
	
	if (refillStartTime < float.MaxValue && refillStartTime + 30 > Time.unscaledTime){
		//only evaluated when the start time is below the maxValue and is reset after the energy increase was applied
		energy += 2;
		refillStartTime = float.MaxValue;
	}

}

You could use TimeSpan.TotalSeconds, but you got to code it a bit differently :

  1. save the moment when you start to
    count time for refill (in savegame,
    so if player kill your application
    and come back, it’s still valid)
  2. use TimeSpan to mesure elapsed time,
    and refill your energy bar
    adequatly.

in code, it would be something like :

		// energy is below 20, so time to refill and you're not already refilling
		DateTime startTimeToRefill;
		if(startTimeToRefill != null)
			startTimeToRefill = DateTime.Now;

		//... save startTimeToRefill in your savegame...

		// mesure time elapsed and find out how much energy has been refilled
		TimeSpan elapsedTime = DateTime.Now - startTimeToRefill;
		int energyGained = elapsedTime.TotalSeconds % 30;