How to make a timer that shows time remaining until an event?

Hello, I am teaching myself Unity and C# and I though I would tackle the, what I thought, simple task of creating an energy system like found in many mobile freemium games.

The idea is to have an amount of “energy”. Doing an action consumes a set amount of energy. Energy refills over time automatically.

With some help on Reddit I got the functionlity working, but now I want to create a timer that shows the time left until the next energy will be gained and there I hit a wall and not sure how to do it. I tried converting TimeSpan to string but I do not get the result I want. I hope I can find some help here.

Thanks!

Here is the code I have so far:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class EnergyTest : MonoBehaviour {

	public Text remainingEnergy;
	public Text timeToNextEnergy;
	
	System.TimeSpan timeRemaining;

	public System.Action<System.TimeSpan> OnTimeRemainingUpdate;

	long lockTime = 0;
	int stamina = 0;
	int maxStamina = 20;
	System.TimeSpan waitTime = new System.TimeSpan(0,0,5);


	public void UseOneStamina(){
		if (stamina > 0){
			lockTime = System.DateTime.Now.Ticks;
			stamina--;
		}
	}

	public void UseFiveStamina(){
		if (stamina > 4){
			lockTime = System.DateTime.Now.Ticks;
			stamina -= 5;
		}
	}

	// Use this for initialization
	void Start () {
		stamina = maxStamina;
	}
	
	// Update is called once per frame
	void Update () {

		if (lockTime > 0){
			while (System.DateTime.Now.Ticks >= lockTime + waitTime.Ticks && stamina < maxStamina){
				stamina++;
				lockTime += waitTime.Ticks;
			}
		}
	
		if (OnTimeRemainingUpdate != null)
		{
			long timeRemainingTicks = lockTime + waitTime.Ticks - System.DateTime.Now.Ticks;
			timeRemaining = new System.TimeSpan(timeRemainingTicks);
			OnTimeRemainingUpdate(timeRemaining);
		}


		System.TimeSpan timeToFill = new System.TimeSpan(lockTime);
		timeToNextEnergy.text = string.Format("{0}:{1}", timeToFill.Minutes, timeToFill.Seconds);
		remainingEnergy.text = stamina + "/" + maxStamina;


	}
}

There’s different kinds of time in unity,

now.milliseconds is much better than ticks, ticks is e^7 per second it’s 3ghz so it’s overkill for measuring energy and ms easier to run maths on.

unity Time.time is very great in unity,

read the different pages of the Time. class and see there are options that are frame times and other that are absolute times.